Task.Wait Metodo

Definizione

Attende il completamento dell'esecuzione di Task.

Overload

Wait()

Attende il completamento dell'esecuzione di Task.

Wait(Int32)

Attende il completamento dell'esecuzione di Task entro un numero specificato di millisecondi.

Wait(CancellationToken)

Attende il completamento dell'esecuzione di Task. L'attesa termina se un token di annullamento viene annullato prima del completamento dell'attività.

Wait(TimeSpan)

Attende il completamento dell'esecuzione di Task entro un intervallo di tempo specificato.

Wait(Int32, CancellationToken)

Attende il completamento dell'esecuzione di Task. L'attesa termina se si esaurisce l'intervallo di timeout o se un token di annullamento viene annullato prima del completamento dell'attività.

Wait(TimeSpan, CancellationToken)

Attende il completamento dell'esecuzione di Task.

Wait()

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Attende il completamento dell'esecuzione di Task.

public:
 void Wait();
public void Wait ();
member this.Wait : unit -> unit
Public Sub Wait ()

Eccezioni

L'interfaccia Task è stata eliminata.

L'attività è stata annullata. La raccolta InnerExceptions contiene un oggetto TaskCanceledException.

-oppure-

È stata generata un'eccezione durante l'esecuzione dell'attività. La raccolta InnerExceptions contiene informazioni su una o più eccezioni.

Esempio

Nell'esempio seguente viene avviata un'attività che genera un milione di numeri interi casuali compresi tra 0 e 100 e ne calcola la media. Nell'esempio viene usato il Wait metodo per assicurarsi che l'attività venga completata prima che l'applicazione termini. In caso contrario, poiché si tratta di un'applicazione console, l'esempio viene terminato prima che l'attività possa calcolare e visualizzare la media.

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Task t = Task.Run( () => {
                            Random rnd = new Random();
                            long sum = 0;
                            int n = 1000000;
                            for (int ctr = 1; ctr <= n; ctr++) {
                               int number = rnd.Next(0, 101);
                               sum += number;
                            }
                            Console.WriteLine("Total:   {0:N0}", sum);
                            Console.WriteLine("Mean:    {0:N2}", sum/n);
                            Console.WriteLine("N:       {0:N0}", n);   
                         } );
     t.Wait();
   }
}
// The example displays output similar to the following:
//       Total:   50,015,714
//       Mean:    50.02
//       N:       1,000,000
open System
open System.Threading.Tasks

let t =
    Task.Run(fun () ->
        let rnd = Random()
        let mutable sum = 0L
        let n = 1000000

        for _ = 1 to n do
            let number = rnd.Next(0, 101)
            sum <- sum + int64 number

        printfn $"Total:   {sum:N0}"
        printfn $"Mean:    {float sum / float n:N2}"
        printfn $"N:       {n:N0}")

t.Wait()

// The example displays output similar to the following:
//       Total:   50,015,714
//       Mean:    50.02
//       N:       1,000,000
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim t As Task = Task.Run( Sub()
                                   Dim rnd As New Random()
                                   Dim sum As Long
                                   Dim n As Integer = 1000000
                                   For ctr As Integer = 1 To n
                                      Dim number As Integer = rnd.Next(0, 101)
                                      sum += number
                                   Next
                                   Console.WriteLine("Total:   {0:N0}", sum)
                                   Console.WriteLine("Mean:    {0:N2}", sum/n)
                                   Console.WriteLine("N:       {0:N0}", n)   
                                End Sub)
     t.Wait()
   End Sub
End Module
' The example displays output similar to the following:
'       Total:   50,015,714
'       Mean:    50.02
'       N:       1,000,000

Commenti

Wait è un metodo di sincronizzazione che fa sì che il thread chiamante attenda il completamento dell'attività corrente. Se l'attività corrente non ha avviato l'esecuzione, il metodo Wait tenta di rimuovere l'attività dall'utilità di pianificazione ed eseguirla inline nel thread corrente. Se non è in grado di eseguire questa operazione o se l'attività corrente ha già avviato l'esecuzione, blocca il thread chiamante fino al completamento dell'attività. Per altre informazioni, vedere Task.Wait e "Inlining" nel blog Programmazione parallela con .NET.

Vedi anche

Si applica a

Wait(Int32)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Attende il completamento dell'esecuzione di Task entro un numero specificato di millisecondi.

public:
 bool Wait(int millisecondsTimeout);
public bool Wait (int millisecondsTimeout);
member this.Wait : int -> bool
Public Function Wait (millisecondsTimeout As Integer) As Boolean

Parametri

millisecondsTimeout
Int32

Numero di millisecondi di attesa oppure Infinite (-1) per un'attesa indefinita.

Restituisce

true se Task ha completato l'esecuzione nel tempo consentito; in caso contrario, false.

Eccezioni

L'interfaccia Task è stata eliminata.

millisecondsTimeout è un numero negativo diverso da -1, che rappresenta un timeout infinito.

L'attività è stata annullata. La raccolta InnerExceptions contiene un oggetto TaskCanceledException.

-oppure-

È stata generata un'eccezione durante l'esecuzione dell'attività. La raccolta InnerExceptions contiene informazioni su una o più eccezioni.

Esempio

Nell'esempio seguente viene avviata un'attività che genera cinque milioni di interi casuali compresi tra 0 e 100 e ne calcola la media. Nell'esempio viene usato il Wait(Int32) metodo per attendere il completamento dell'applicazione entro 150 millisecondi. Se l'applicazione viene completata normalmente, l'attività visualizza la somma e la media dei numeri casuali generati. Se è trascorso l'intervallo di timeout, nell'esempio viene visualizzato un messaggio prima che venga terminato.

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Task t = Task.Run( () => {
                            Random rnd = new Random();
                            long sum = 0;
                            int n = 5000000;
                            for (int ctr = 1; ctr <= n; ctr++) {
                               int number = rnd.Next(0, 101);
                               sum += number;
                            }
                            Console.WriteLine("Total:   {0:N0}", sum);
                            Console.WriteLine("Mean:    {0:N2}", sum/n);
                            Console.WriteLine("N:       {0:N0}", n);   
                         } );
     if (! t.Wait(150))
        Console.WriteLine("The timeout interval elapsed.");
   }
}
// The example displays output similar to the following:
//       Total:   50,015,714
//       Mean:    50.02
//       N:       1,000,000
// Or it displays the following output:
//      The timeout interval elapsed.
open System
open System.Threading.Tasks

let t =
    Task.Run(fun () ->
        let rnd = Random()
        let mutable sum = 0L
        let n = 5000000

        for _ = 1 to n do
            let number = rnd.Next(0, 101)
            sum <- sum + int64 number

        printfn $"Total:   {sum:N0}"
        printfn $"Mean:    {float sum / float n:N2}"
        printfn $"N:       {n:N0}")

if t.Wait 150 |> not then
    printfn "The timeout interval elapsed."

// The example displays output similar to the following:
//       Total:   50,015,714
//       Mean:    50.02
//       N:       1,000,000
// Or it displays the following output:
//      The timeout interval elapsed.
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim t As Task = Task.Run( Sub()
                                   Dim rnd As New Random()
                                   Dim sum As Long
                                   Dim n As Integer = 5000000
                                   For ctr As Integer = 1 To n
                                      Dim number As Integer = rnd.Next(0, 101)
                                      sum += number
                                   Next
                                   Console.WriteLine("Total:   {0:N0}", sum)
                                   Console.WriteLine("Mean:    {0:N2}", sum/n)
                                   Console.WriteLine("N:       {0:N0}", n)   
                                End Sub)
     If Not t.Wait(150) Then
        Console.WriteLine("The timeout interval elapsed.")
     End If
   End Sub
End Module
' The example displays output similar to the following:
'       Total:   50,015,714
'       Mean:    50.02
'       N:       1,000,000
' Or it displays the following output:
'       The timeout interval elapsed.

Commenti

Wait(Int32) è un metodo di sincronizzazione che fa sì che il thread chiamante attenda il completamento dell'istanza dell'attività corrente fino a quando non si verifica una delle operazioni seguenti:

  • L'attività viene completata correttamente.

  • L'attività stessa viene annullata o genera un'eccezione. In questo caso, si gestisce un'eccezione AggregateException . La AggregateException.InnerExceptions proprietà contiene informazioni dettagliate sull'eccezione o sulle eccezioni.

  • Intervallo definito da millisecondsTimeout trascorsi. In questo caso, il thread corrente riprende l'esecuzione e il metodo restituisce false.

Si applica a

Wait(CancellationToken)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Attende il completamento dell'esecuzione di Task. L'attesa termina se un token di annullamento viene annullato prima del completamento dell'attività.

public:
 void Wait(System::Threading::CancellationToken cancellationToken);
public void Wait (System.Threading.CancellationToken cancellationToken);
member this.Wait : System.Threading.CancellationToken -> unit
Public Sub Wait (cancellationToken As CancellationToken)

Parametri

cancellationToken
CancellationToken

Token di annullamento da osservare durante l'attesa del completamento dell'attività.

Eccezioni

Il parametro cancellationToken è stato annullato.

L'attività è stata eliminata.

L'attività è stata annullata. La raccolta InnerExceptions contiene un oggetto TaskCanceledException.

-oppure-

È stata generata un'eccezione durante l'esecuzione dell'attività. La raccolta InnerExceptions contiene informazioni su una o più eccezioni.

Esempio

Nell'esempio seguente viene illustrato l'uso semplice di un token di annullamento per annullare l'attesa del completamento di un'attività. Viene avviata un'attività, chiama il CancellationTokenSource.Cancel metodo per annullare uno dei token di annullamento dell'origine del token e quindi ritarda per cinque secondi. Si noti che l'attività stessa non è stata passata al token di annullamento e non è annullabile. Il thread dell'applicazione chiama il metodo dell'attività Task.Wait per attendere il completamento dell'attività, ma l'attesa viene annullata dopo l'annullamento del token di annullamento e viene generata un'eccezione OperationCanceledException . Il gestore eccezioni segnala l'eccezione e quindi dorme per sei secondi. Come illustrato nell'output dell'esempio, questo ritardo consente il completamento dell'attività RanToCompletion nello stato .

using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      CancellationTokenSource ts = new CancellationTokenSource();

      Task t = Task.Run( () => { Console.WriteLine("Calling Cancel...");
                                 ts.Cancel();
                                 Task.Delay(5000).Wait();
                                 Console.WriteLine("Task ended delay...");
                               });
      try {
         Console.WriteLine("About to wait for the task to complete...");
         t.Wait(ts.Token);
      }
      catch (OperationCanceledException e) {
         Console.WriteLine("{0}: The wait has been canceled. Task status: {1:G}",
                           e.GetType().Name, t.Status);
         Thread.Sleep(6000);
         Console.WriteLine("After sleeping, the task status:  {0:G}", t.Status);
      }
      ts.Dispose();
   }
}
// The example displays output like the following:
//    About to wait for the task to complete...
//    Calling Cancel...
//    OperationCanceledException: The wait has been canceled. Task status: Running
//    Task ended delay...
//    After sleeping, the task status:  RanToCompletion
open System
open System.Threading
open System.Threading.Tasks

let ts = new CancellationTokenSource()

let t =
    Task.Run(fun () ->
        printfn "Calling Cancel..."
        ts.Cancel()
        Task.Delay(5000).Wait()
        printfn $"Task ended delay...")

try
    printfn "About to wait for the task to complete..."
    t.Wait ts.Token

with :? OperationCanceledException as e ->
    printfn $"{e.GetType().Name}: The wait has been canceled. Task status: {t.Status:G}"
    Thread.Sleep 6000
    printfn $"After sleeping, the task status:  {t.Status:G}"

ts.Dispose()


// The example displays output like the following:
//    About to wait for the task to complete...
//    Calling Cancel...
//    OperationCanceledException: The wait has been canceled. Task status: Running
//    Task ended delay...
//    After sleeping, the task status:  RanToCompletion
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim ts As New CancellationTokenSource()

      Dim t = Task.Run( Sub()
                           Console.WriteLine("Calling Cancel...")
                           ts.Cancel()
                           Task.Delay(5000).Wait()
                           Console.WriteLine("Task ended delay...")
                        End Sub)
      Try
         Console.WriteLine("About to wait for the task to complete...")
         t.Wait(ts.Token)
      Catch e As OperationCanceledException
         Console.WriteLine("{0}: The wait has been canceled. Task status: {1:G}",
                           e.GetType().Name, t.Status)
         Thread.Sleep(6000)
         Console.WriteLine("After sleeping, the task status:  {0:G}", t.Status)
      End Try
      ts.Dispose()
   End Sub
End Module
' The example displays output like the following:
'    About to wait for the task to complete...
'    Calling Cancel...
'    OperationCanceledException: The wait has been canceled. Task status: Running
'    Task ended delay...
'    After sleeping, the task status:  RanToCompletion

Commenti

Il Wait(CancellationToken) metodo crea un'attesa annullabile, ovvero fa sì che il thread corrente attenda fino a quando non si verifica una delle operazioni seguenti:

Nota

L'annullamento del cancellationToken token di annullamento non ha alcun effetto sull'attività in esecuzione, a meno che non sia stato passato anche il token di annullamento ed è pronto per gestire l'annullamento. Il passaggio dell'oggetto cancellationToken a questo metodo consente semplicemente di annullare l'attesa.

Si applica a

Wait(TimeSpan)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Attende il completamento dell'esecuzione di Task entro un intervallo di tempo specificato.

public:
 bool Wait(TimeSpan timeout);
public bool Wait (TimeSpan timeout);
member this.Wait : TimeSpan -> bool
Public Function Wait (timeout As TimeSpan) As Boolean

Parametri

timeout
TimeSpan

Oggetto TimeSpan che rappresenta il numero di millisecondi di attesa oppure TimeSpan che rappresenta -1 millisecondi per un'attesa indefinita.

Restituisce

true se Task ha completato l'esecuzione nel tempo consentito; in caso contrario, false.

Eccezioni

L'interfaccia Task è stata eliminata.

timeout è un numero negativo diverso da -1 millisecondi, che rappresenta un timeout infinito.

-oppure-

timeout è maggiore di Int32.MaxValue.

L'attività è stata annullata. La raccolta InnerExceptions contiene un oggetto TaskCanceledException.

-oppure-

È stata generata un'eccezione durante l'esecuzione dell'attività. La raccolta InnerExceptions contiene informazioni su una o più eccezioni.

Esempio

Nell'esempio seguente viene avviata un'attività che genera cinque milioni di interi casuali compresi tra 0 e 100 e ne calcola la media. Nell'esempio viene usato il Wait(TimeSpan) metodo per attendere il completamento dell'applicazione entro 150 millisecondi. Se l'applicazione viene completata normalmente, l'attività visualizza la somma e la media dei numeri casuali generati. Se è trascorso l'intervallo di timeout, nell'esempio viene visualizzato un messaggio prima che venga terminato.

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Task t = Task.Run( () => {
                            Random rnd = new Random();
                            long sum = 0;
                            int n = 5000000;
                            for (int ctr = 1; ctr <= n; ctr++) {
                               int number = rnd.Next(0, 101);
                               sum += number;
                            }
                            Console.WriteLine("Total:   {0:N0}", sum);
                            Console.WriteLine("Mean:    {0:N2}", sum/n);
                            Console.WriteLine("N:       {0:N0}", n);   
                         } );
     TimeSpan ts = TimeSpan.FromMilliseconds(150);
     if (! t.Wait(ts))
        Console.WriteLine("The timeout interval elapsed.");
   }
}
// The example displays output similar to the following:
//       Total:   50,015,714
//       Mean:    50.02
//       N:       1,000,000
// Or it displays the following output:
//      The timeout interval elapsed.
open System
open System.Threading.Tasks

let t =
    Task.Run(fun () ->
        let rnd = Random()
        let mutable sum = 0L
        let n = 5000000

        for _ = 1 to n do
            let number = rnd.Next(0, 101)
            sum <- sum + int64 number

        printfn $"Total:   {sum:N0}"
        printfn $"Mean:    {float sum / float n:N2}"
        printfn $"N:       {n:N0}")

let ts = TimeSpan.FromMilliseconds 150

if t.Wait ts |> not then
    printfn "The timeout interval elapsed."

// The example displays output similar to the following:
//       Total:   50,015,714
//       Mean:    50.02
//       N:       1,000,000
// Or it displays the following output:
//      The timeout interval elapsed.
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim t As Task = Task.Run( Sub()
                                   Dim rnd As New Random()
                                   Dim sum As Long
                                   Dim n As Integer = 5000000
                                   For ctr As Integer = 1 To n
                                      Dim number As Integer = rnd.Next(0, 101)
                                      sum += number
                                   Next
                                   Console.WriteLine("Total:   {0:N0}", sum)
                                   Console.WriteLine("Mean:    {0:N2}", sum/n)
                                   Console.WriteLine("N:       {0:N0}", n)   
                                End Sub)
     Dim ts As TimeSpan = TimeSpan.FromMilliseconds(150)
     If Not t.Wait(ts) Then
        Console.WriteLine("The timeout interval elapsed.")
     End If
   End Sub
End Module
' The example displays output similar to the following:
'       Total:   50,015,714
'       Mean:    50.02
'       N:       1,000,000
' Or it displays the following output:
'       The timeout interval elapsed.

Commenti

Wait(TimeSpan) è un metodo di sincronizzazione che fa sì che il thread chiamante attenda il completamento dell'istanza dell'attività corrente fino a quando non si verifica una delle operazioni seguenti:

  • L'attività viene completata correttamente.

  • L'attività stessa viene annullata o genera un'eccezione. In questo caso, si gestisce un'eccezione AggregateException . La AggregateException.InnerExceptions proprietà contiene informazioni dettagliate sull'eccezione o sulle eccezioni.

  • Intervallo definito da timeout trascorsi. In questo caso, il thread corrente riprende l'esecuzione e il metodo restituisce false.

Si applica a

Wait(Int32, CancellationToken)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Attende il completamento dell'esecuzione di Task. L'attesa termina se si esaurisce l'intervallo di timeout o se un token di annullamento viene annullato prima del completamento dell'attività.

public:
 bool Wait(int millisecondsTimeout, System::Threading::CancellationToken cancellationToken);
public bool Wait (int millisecondsTimeout, System.Threading.CancellationToken cancellationToken);
member this.Wait : int * System.Threading.CancellationToken -> bool
Public Function Wait (millisecondsTimeout As Integer, cancellationToken As CancellationToken) As Boolean

Parametri

millisecondsTimeout
Int32

Numero di millisecondi di attesa oppure Infinite (-1) per un'attesa indefinita.

cancellationToken
CancellationToken

Token di annullamento da osservare durante l'attesa del completamento dell'attività.

Restituisce

true se Task ha completato l'esecuzione nel tempo consentito; in caso contrario, false.

Eccezioni

Il parametro cancellationToken è stato annullato.

L'interfaccia Task è stata eliminata.

millisecondsTimeout è un numero negativo diverso da -1, che rappresenta un timeout infinito.

L'attività è stata annullata. La raccolta InnerExceptions contiene un oggetto TaskCanceledException.

-oppure-

È stata generata un'eccezione durante l'esecuzione dell'attività. La raccolta InnerExceptions contiene informazioni su una o più eccezioni.

Esempio

Nell'esempio seguente viene chiamato il Wait(Int32, CancellationToken) metodo per fornire sia un valore di timeout che un token di annullamento che può terminare l'attesa del completamento di un'attività. Viene avviato un nuovo thread ed esegue il metodo, che sospende e quindi chiama il CancelTokenCancellationTokenSource.Cancel metodo per annullare i token di annullamento. Un'attività viene quindi avviata e ritarda per 5 secondi. Il Wait metodo viene quindi chiamato per attendere il completamento dell'attività e viene fornito sia un breve valore di timeout che un token di annullamento.

using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      CancellationTokenSource ts = new CancellationTokenSource();
      Thread thread = new Thread(CancelToken);
      thread.Start(ts);

      Task t = Task.Run( () => { Task.Delay(5000).Wait();
                                 Console.WriteLine("Task ended delay...");
                               });
      try {
         Console.WriteLine("About to wait completion of task {0}", t.Id);
         bool result = t.Wait(1510, ts.Token);
         Console.WriteLine("Wait completed normally: {0}", result);
         Console.WriteLine("The task status:  {0:G}", t.Status);
      }
      catch (OperationCanceledException e) {
         Console.WriteLine("{0}: The wait has been canceled. Task status: {1:G}",
                           e.GetType().Name, t.Status);
         Thread.Sleep(4000);
         Console.WriteLine("After sleeping, the task status:  {0:G}", t.Status);
         ts.Dispose();
      }
   }

   private static void CancelToken(Object obj)
   {
      Thread.Sleep(1500);
      Console.WriteLine("Canceling the cancellation token from thread {0}...",
                        Thread.CurrentThread.ManagedThreadId);
      CancellationTokenSource source = obj as CancellationTokenSource;
      if (source != null) source.Cancel();
   }
}
// The example displays output like the following if the wait is canceled by
// the cancellation token:
//    About to wait completion of task 1
//    Canceling the cancellation token from thread 3...
//    OperationCanceledException: The wait has been canceled. Task status: Running
//    Task ended delay...
//    After sleeping, the task status:  RanToCompletion
// The example displays output like the following if the wait is canceled by
// the timeout interval expiring:
//    About to wait completion of task 1
//    Wait completed normally: False
//    The task status:  Running
//    Canceling the cancellation token from thread 3...
open System
open System.Threading
open System.Threading.Tasks

let cancelToken (obj: obj) =
    Thread.Sleep 1500
    printfn $"Canceling the cancellation token from thread {Thread.CurrentThread.ManagedThreadId}..."

    match obj with
    | :? CancellationTokenSource as source -> source.Cancel()
    | _ -> ()

let ts = new CancellationTokenSource()
let thread = Thread(ParameterizedThreadStart cancelToken)
thread.Start ts

let t =
    Task.Run(fun () ->
        Task.Delay(5000).Wait()
        printfn "Task ended delay...")

try
    printfn $"About to wait completion of task {t.Id}"
    let result = t.Wait(1510, ts.Token)
    printfn $"Wait completed normally: {result}"
    printfn $"The task status:  {t.Status:G}"

with :? OperationCanceledException as e ->
    printfn $"{e.GetType().Name}: The wait has been canceled. Task status: {t.Status:G}"
    Thread.Sleep 4000
    printfn $"After sleeping, the task status:  {t.Status:G}"
    ts.Dispose()

// The example displays output like the following if the wait is canceled by
// the cancellation token:
//    About to wait completion of task 1
//    Canceling the cancellation token from thread 3...
//    OperationCanceledException: The wait has been canceled. Task status: Running
//    Task ended delay...
//    After sleeping, the task status:  RanToCompletion
// The example displays output like the following if the wait is canceled by
// the timeout interval expiring:
//    About to wait completion of task 1
//    Wait completed normally: False
//    The task status:  Running
//    Canceling the cancellation token from thread 3...
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim ts As New CancellationTokenSource()
      Dim thread As New Thread(AddressOf CancelToken)
      thread.Start(ts)

      Dim t As Task = Task.Run( Sub()
                                   Task.Delay(5000).Wait()
                                    Console.WriteLine("Task ended delay...")
                                End Sub)
      Try
         Console.WriteLine("About to wait completion of task {0}", t.Id)
         Dim result As Boolean = t.Wait(1510, ts.Token)
         Console.WriteLine("Wait completed normally: {0}", result)
         Console.WriteLine("The task status:  {0:G}", t.Status)
      Catch e As OperationCanceledException
         Console.WriteLine("{0}: The wait has been canceled. Task status: {1:G}",
                           e.GetType().Name, t.Status)
         Thread.Sleep(4000)
         Console.WriteLine("After sleeping, the task status:  {0:G}", t.Status)
         ts.Dispose()
      End Try
   End Sub

   Private Sub CancelToken(obj As Object)
      Thread.Sleep(1500)
      Console.WriteLine("Canceling the cancellation token from thread {0}...",
                        Thread.CurrentThread.ManagedThreadId)

      If TypeOf obj Is CancellationTokenSource Then
         Dim source As CancellationTokenSource = CType(obj, CancellationTokenSource)
         source.Cancel()
      End If
   End Sub
End Module
' The example displays output like the following if the wait is canceled by
' the cancellation token:
'    About to wait completion of task 1
'    Canceling the cancellation token from thread 3...
'    OperationCanceledException: The wait has been canceled. Task status: Running
'    Task ended delay...
'    After sleeping, the task status:  RanToCompletion
' The example displays output like the following if the wait is canceled by
' the timeout interval expiring:
'    About to wait completion of task 1
'    Wait completed normally: False
'    The task status:  Running
'    Canceling the cancellation token from thread 3...

Si noti che l'output preciso dell'esempio dipende dal fatto che l'attesa sia stata annullata a causa del token di annullamento o perché l'intervallo di timeout trascorso.

Commenti

Wait(Int32, CancellationToken) è un metodo di sincronizzazione che causa l'attesa del thread chiamante per il completamento dell'istanza dell'attività corrente fino a quando non si verifica una delle operazioni seguenti:

  • L'attività viene completata correttamente.

  • L'attività stessa viene annullata o genera un'eccezione. In questo caso, si gestisce un'eccezione AggregateException . La AggregateException.InnerExceptions proprietà contiene dettagli sull'eccezione o sulle eccezioni.

  • Il cancellationToken token di annullamento viene annullato. In questo caso, la chiamata al Wait(Int32, CancellationToken) metodo genera un OperationCanceledExceptionoggetto .

  • Intervallo definito da millisecondsTimeout trascorsi. In questo caso, il thread corrente riprende l'esecuzione e il metodo restituisce false.

Nota

L'annullamento del cancellationToken token di annullamento non ha alcun effetto sull'attività in esecuzione, a meno che non sia stato passato anche il token di annullamento e sia stato preparato per gestire l'annullamento. Il passaggio dell'oggetto a questo metodo consente semplicemente di annullare l'attesa cancellationToken in base a una condizione.

Si applica a

Wait(TimeSpan, CancellationToken)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Attende il completamento dell'esecuzione di Task.

public:
 bool Wait(TimeSpan timeout, System::Threading::CancellationToken cancellationToken);
public bool Wait (TimeSpan timeout, System.Threading.CancellationToken cancellationToken);
member this.Wait : TimeSpan * System.Threading.CancellationToken -> bool
Public Function Wait (timeout As TimeSpan, cancellationToken As CancellationToken) As Boolean

Parametri

timeout
TimeSpan

Tempo di attesa o InfiniteTimeSpan attesa indefinita

cancellationToken
CancellationToken

Oggetto CancellationToken da osservare durante l'attesa del completamento dell'attività.

Restituisce

true se Task ha completato l'esecuzione nel tempo consentito; in caso contrario, false.

Eccezioni

L'oggetto Task è stato annullato

-oppure-

un'eccezione è stata generata durante l'esecuzione Taskdi .

timeout è un numero negativo diverso da -1 millisecondi, che rappresenta un timeout infinito

-oppure-

timeout è maggiore di MaxValue.

Il parametro cancellationToken è stato annullato.

Si applica a