Task.Wait Método

Definição

Aguarda o Task concluir a execução.

Sobrecargas

Wait()

Aguarda o Task concluir a execução.

Wait(Int32)

Aguarda o Task concluir a execução dentro de um número especificado. de milissegundos.

Wait(CancellationToken)

Aguarda o Task concluir a execução. A espera termina se um token de cancelamento for cancelado antes que a tarefa seja concluída.

Wait(TimeSpan)

Aguarda o Task concluir a execução dentro de um intervalo especificado.

Wait(Int32, CancellationToken)

Aguarda o Task concluir a execução. A espera termina se um intervalo de tempo limite expirar ou um token de cancelamento for cancelado antes que a tarefa seja concluída.

Wait(TimeSpan, CancellationToken)

Aguarda o Task concluir a execução.

Wait()

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

Aguarda o Task concluir a execução.

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

Exceções

O Task foi descartado.

A tarefa foi cancelada. A coleção InnerExceptions contém um objeto TaskCanceledException.

- ou -

Uma exceção foi gerada durante a execução da tarefa. A coleção InnerExceptions contém informações sobre a exceção ou as exceções.

Exemplos

O exemplo a seguir inicia uma tarefa que gera um milhão de inteiros aleatórios entre 0 e 100 e calcula sua média. O exemplo usa o Wait método para garantir que a tarefa seja concluída antes que o aplicativo seja encerrado. Caso contrário, como esse é um aplicativo de console, o exemplo terminaria antes que a tarefa possa calcular e exibir a média.

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

Comentários

Wait é um método de sincronização que faz com que o thread de chamada aguarde até que a tarefa atual seja concluída. Se a tarefa atual não tiver iniciado a execução, o método Wait tentará remover a tarefa do agendador e executá-la embutida no thread atual. Se não for possível fazer isso ou se a tarefa atual já tiver iniciado a execução, ela bloqueará o thread de chamada até que a tarefa seja concluída. Para obter mais informações, consulte Task.Wait e "Inlining" no blog Programação Paralela com .NET.

Confira também

Aplica-se a

Wait(Int32)

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

Aguarda o Task concluir a execução dentro de um número especificado. de milissegundos.

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

Parâmetros

millisecondsTimeout
Int32

O número de milissegundos para aguardar ou Infinite (- 1) para aguardar indefinidamente.

Retornos

true se o Task concluiu a execução dentro do tempo determinado; caso contrário, false.

Exceções

O Task foi descartado.

millisecondsTimeout é um número negativo diferente de -1, que representa um tempo limite infinito.

A tarefa foi cancelada. A coleção InnerExceptions contém um objeto TaskCanceledException.

- ou -

Uma exceção foi gerada durante a execução da tarefa. A coleção InnerExceptions contém informações sobre a exceção ou as exceções.

Exemplos

O exemplo a seguir inicia uma tarefa que gera cinco milhões de inteiros aleatórios entre 0 e 100 e calcula sua média. O exemplo usa o Wait(Int32) método para aguardar a conclusão do aplicativo dentro de 150 milissegundos. Se o aplicativo for concluído normalmente, a tarefa exibirá a soma e a média dos números aleatórios gerados. Se o intervalo de tempo limite tiver decorrido, o exemplo exibirá uma mensagem antes de terminar.

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.

Comentários

Wait(Int32) é um método de sincronização que faz com que o thread de chamada aguarde a conclusão da instância de tarefa atual até que ocorra um destes procedimentos:

  • A tarefa é concluída com êxito.

  • A tarefa em si é cancelada ou gera uma exceção. Nesse caso, você manipula uma exceção AggregateException . A AggregateException.InnerExceptions propriedade contém detalhes sobre a exceção ou exceções.

  • O intervalo definido por millisecondsTimeout decorridos. Nesse caso, o thread atual retoma a execução e o método retorna false.

Aplica-se a

Wait(CancellationToken)

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

Aguarda o Task concluir a execução. A espera termina se um token de cancelamento for cancelado antes que a tarefa seja concluída.

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)

Parâmetros

cancellationToken
CancellationToken

Um token de cancelamento a ser observado ao aguardar a conclusão da tarefa.

Exceções

O cancellationToken foi cancelado.

A tarefa foi descartada.

A tarefa foi cancelada. A coleção InnerExceptions contém um objeto TaskCanceledException.

- ou -

Uma exceção foi gerada durante a execução da tarefa. A coleção InnerExceptions contém informações sobre a exceção ou as exceções.

Exemplos

O exemplo a seguir ilustra o uso simples de um token de cancelamento para cancelar aguardando a conclusão de uma tarefa. Uma tarefa é iniciada, chama o CancellationTokenSource.Cancel método para cancelar qualquer um dos tokens de cancelamento da origem do token e, em seguida, atrasa por cinco segundos. Observe que a tarefa em si não foi passada para o token de cancelamento e não é cancelável. O thread do aplicativo chama o método da tarefa para aguardar a conclusão da Task.Wait tarefa, mas a espera é cancelada depois que o token de cancelamento é cancelado e um OperationCanceledException é gerado. O manipulador de exceção relata a exceção e, em seguida, dorme por seis segundos. Como mostra a saída do exemplo, esse atraso permite que a tarefa seja concluída no RanToCompletion estado .

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

Comentários

O Wait(CancellationToken) método cria uma espera cancelável; ou seja, faz com que o thread atual aguarde até que ocorra um destes procedimentos:

Observação

Cancelar o cancellationToken token de cancelamento não tem efeito na tarefa em execução, a menos que ele também tenha sido passado o token de cancelamento e esteja preparado para lidar com o cancelamento. Passar o cancellationToken objeto para esse método simplesmente permite que a espera seja cancelada.

Aplica-se a

Wait(TimeSpan)

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

Aguarda o Task concluir a execução dentro de um intervalo especificado.

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

Parâmetros

timeout
TimeSpan

Um TimeSpan que representa o número de milissegundos para aguardar ou um TimeSpan que representa -1 milissegundos para aguardar indefinidamente.

Retornos

true se o Task concluiu a execução dentro do tempo determinado; caso contrário, false.

Exceções

O Task foi descartado.

timeout é um número negativo diferente de -1 milissegundo, que representa um tempo limite infinito.

- ou -

timeout é maior que Int32.MaxValue.

A tarefa foi cancelada. A coleção InnerExceptions contém um objeto TaskCanceledException.

- ou -

Uma exceção foi gerada durante a execução da tarefa. A coleção InnerExceptions contém informações sobre a exceção ou as exceções.

Exemplos

O exemplo a seguir inicia uma tarefa que gera cinco milhões de inteiros aleatórios entre 0 e 100 e calcula sua média. O exemplo usa o Wait(TimeSpan) método para aguardar a conclusão do aplicativo dentro de 150 milissegundos. Se o aplicativo for concluído normalmente, a tarefa exibirá a soma e a média dos números aleatórios gerados. Se o intervalo de tempo limite tiver decorrido, o exemplo exibirá uma mensagem antes de terminar.

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.

Comentários

Wait(TimeSpan) é um método de sincronização que faz com que o thread de chamada aguarde a conclusão da instância de tarefa atual até que ocorra um destes procedimentos:

  • A tarefa é concluída com êxito.

  • A tarefa em si é cancelada ou gera uma exceção. Nesse caso, você manipula uma exceção AggregateException . A AggregateException.InnerExceptions propriedade contém detalhes sobre a exceção ou exceções.

  • O intervalo definido por timeout decorridos. Nesse caso, o thread atual retoma a execução e o método retorna false.

Aplica-se a

Wait(Int32, CancellationToken)

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

Aguarda o Task concluir a execução. A espera termina se um intervalo de tempo limite expirar ou um token de cancelamento for cancelado antes que a tarefa seja concluída.

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

Parâmetros

millisecondsTimeout
Int32

O número de milissegundos para aguardar ou Infinite (- 1) para aguardar indefinidamente.

cancellationToken
CancellationToken

Um token de cancelamento a ser observado ao aguardar a conclusão da tarefa.

Retornos

true se o Task concluiu a execução dentro do tempo determinado; caso contrário, false.

Exceções

O cancellationToken foi cancelado.

O Task foi descartado.

millisecondsTimeout é um número negativo diferente de -1, que representa um tempo limite infinito.

A tarefa foi cancelada. A coleção InnerExceptions contém um objeto TaskCanceledException.

- ou -

Uma exceção foi gerada durante a execução da tarefa. A coleção InnerExceptions contém informações sobre a exceção ou as exceções.

Exemplos

O exemplo a seguir chama o Wait(Int32, CancellationToken) método para fornecer um valor de tempo limite e um token de cancelamento que pode encerrar a espera pela conclusão de uma tarefa. Um novo thread é iniciado e executa o CancelToken método , que pausa e chama o CancellationTokenSource.Cancel método para cancelar os tokens de cancelamento. Em seguida, uma tarefa é iniciada e demora 5 segundos. Em Wait seguida, o método é chamado para aguardar a conclusão da tarefa e recebe um breve valor de tempo limite e um token de cancelamento.

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...

Observe que a saída precisa do exemplo depende se a espera foi cancelada devido ao token de cancelamento ou porque o intervalo de tempo limite expirou.

Comentários

Wait(Int32, CancellationToken) é um método de sincronização que faz com que o thread de chamada aguarde a conclusão da instância de tarefa atual até que ocorra um destes procedimentos:

  • A tarefa é concluída com êxito.

  • A tarefa em si é cancelada ou gera uma exceção. Nesse caso, você manipula uma exceção AggregateException . A AggregateException.InnerExceptions propriedade contém detalhes sobre a exceção ou exceções.

  • O cancellationToken token de cancelamento é cancelado. Nesse caso, a chamada para o Wait(Int32, CancellationToken) método lança um OperationCanceledException.

  • O intervalo definido por millisecondsTimeout decorridos. Nesse caso, o thread atual retoma a execução e o método retorna false.

Observação

Cancelar o cancellationToken token de cancelamento não tem efeito sobre a tarefa em execução, a menos que ele também tenha sido passado o token de cancelamento e esteja preparado para lidar com o cancelamento. Passar o cancellationToken objeto para esse método simplesmente permite que a espera seja cancelada com base em alguma condição.

Aplica-se a

Wait(TimeSpan, CancellationToken)

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

Aguarda o Task concluir a execução.

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

Parâmetros

timeout
TimeSpan

O tempo de espera ou InfiniteTimeSpan aguardar indefinidamente

cancellationToken
CancellationToken

Um CancellationToken a ser observado enquanto aguarda a conclusão da tarefa.

Retornos

true se o Task concluiu a execução dentro do tempo determinado; caso contrário, false.

Exceções

O Task foi cancelado

-ou-

uma exceção foi gerada durante a execução do Task.

timeout é um número negativo diferente de -1 milissegundos, que representa um tempo limite infinito

-ou-

tempo excedido é maior que MaxValue.

O cancellationToken foi cancelado.

Aplica-se a