Task.Wait Método

Definição

Espera que a Task execução seja concluída.

Sobrecargas

Name Description
Wait(TimeSpan)

Espera que a Task execução seja concluída dentro de um intervalo de tempo especificado.

Wait(Int32, CancellationToken)

Espera que a Task execução seja concluída. A espera termina se passar um intervalo de tempo ou se um token de cancelamento for cancelado antes da tarefa ser concluída.

Wait(CancellationToken)

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

Wait(Int32)

Espera que a Task execução seja concluída dentro de um número especificado de milissegundos.

Wait()

Espera que a Task execução seja concluída.

Wait(TimeSpan)

Espera que a Task execução seja concluída dentro de um intervalo de tempo 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

A TimeSpan que representa o número de milissegundos para esperar, ou a TimeSpan que representa -1 milissegundos para esperar indefinidamente.

Devoluções

true se a execução concluída Task dentro do tempo estipulado; caso contrário, false.

Exceções

O Task foi descartado.

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

-ou-

timeout é maior do que Int32.MaxValue.

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

-ou-

Foi lançada uma exceção durante a execução da tarefa. A InnerExceptions coleção contém informações sobre a exceção ou exceções.

Exemplos

O exemplo seguinte inicia uma tarefa que gera cinco milhões de inteiros aleatórios entre 0 e 100 e calcula a sua média. O exemplo utiliza o Wait(TimeSpan) método para esperar que a aplicação seja concluída dentro de 150 milissegundos. Se a aplicação for concluída normalmente, a tarefa mostra a soma e a média dos números aleatórios que gerou. Se o intervalo de tempo expirado já passou, o exemplo apresenta 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.

Observações

Wait(TimeSpan) é um método de sincronização que faz com que o thread que chama espere que a instância atual da tarefa seja concluída até que ocorra uma das seguintes situações:

  • A tarefa é concluída com sucesso.

  • A tarefa em si é cancelada ou lança uma exceção. Neste caso, trata de uma AggregateException exceção. A AggregateException.InnerExceptions propriedade contém detalhes sobre a exceção ou exceções.

  • O intervalo definido pelos timeout elapses. Neste caso, o thread atual retoma a execução e o método devolve false.

Aplica-se a

Wait(Int32, CancellationToken)

Espera que a Task execução seja concluída. A espera termina se passar um intervalo de tempo ou se um token de cancelamento for cancelado antes da tarefa ser 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 esperar, ou Infinite (-1) para esperar indefinidamente.

cancellationToken
CancellationToken

Um token de cancelamento para observar enquanto se espera que a tarefa seja concluída.

Devoluções

true se a execução concluída Task dentro do tempo estipulado; caso contrário, false.

Exceções

O cancellationToken foi cancelado.

O Task foi descartado.

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

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

-ou-

Foi lançada uma exceção durante a execução da tarefa. A InnerExceptions coleção contém informações sobre a exceção ou exceções.

Exemplos

O exemplo seguinte chama o Wait(Int32, CancellationToken) método para fornecer tanto um valor de timeout como um token de cancelamento que pode terminar a espera pela conclusão de uma tarefa. Inicia-se uma nova thread e executa o CancelToken método, que pausa e depois chama o CancellationTokenSource.Cancel método para cancelar os tokens de cancelamento. Uma tarefa é então lançada e atrasa-se durante 5 segundos. O Wait método é então chamado para esperar a conclusão da tarefa e recebe tanto um valor de tempo limite breve como 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...

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

Observações

Wait(Int32, CancellationToken) é um método de sincronização que faz com que o thread que chama espere que a instância atual da tarefa seja concluída até que ocorra uma das seguintes situações:

Note

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

Aplica-se a

Wait(CancellationToken)

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

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 para observar enquanto se espera que a tarefa seja concluída.

Exceções

O cancellationToken foi cancelado.

A tarefa foi resolvida.

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

-ou-

Foi lançada uma exceção durante a execução da tarefa. A InnerExceptions coleção contém informações sobre a exceção ou exceções.

Exemplos

O exemplo seguinte ilustra o uso simples de um token de cancelamento para cancelar a espera da conclusão de uma tarefa. É lançada uma tarefa, chama o CancellationTokenSource.Cancel método para cancelar qualquer token de cancelamento da fonte do token e depois atrasa-se durante cinco segundos. Note que a tarefa em si não foi passada pelo token de cancelamento e não é cancelável. O thread da aplicação chama o método da Task.Wait tarefa para esperar que a tarefa seja concluída, mas a espera é cancelada assim que o token de cancelamento é cancelado e um OperationCanceledException é lançado. O gestor de exceções reporta a exceção e depois entra em suspensão durante seis segundos. Como o resultado do exemplo mostra, 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

Observações

O Wait(CancellationToken) método cria uma espera cancelável; ou seja, faz com que o thread atual espere até que ocorra uma das seguintes situações:

Note

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

Aplica-se a

Wait(Int32)

Espera que a Task execução seja concluída 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 esperar, ou Infinite (-1) para esperar indefinidamente.

Devoluções

true se a execução concluída Task dentro do tempo estipulado; caso contrário, false.

Exceções

O Task foi descartado.

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

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

-ou-

Foi lançada uma exceção durante a execução da tarefa. A InnerExceptions coleção contém informações sobre a exceção ou exceções.

Exemplos

O exemplo seguinte inicia uma tarefa que gera cinco milhões de inteiros aleatórios entre 0 e 100 e calcula a sua média. O exemplo utiliza o Wait(Int32) método para esperar que a aplicação seja concluída dentro de 150 milissegundos. Se a aplicação for concluída normalmente, a tarefa mostra a soma e a média dos números aleatórios que gerou. Se o intervalo de tempo expirado já passou, o exemplo apresenta 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.

Observações

Wait(Int32) é um método de sincronização que faz com que o thread que chama espere que a instância atual da tarefa seja concluída até que ocorra uma das seguintes situações:

  • A tarefa é concluída com sucesso.

  • A tarefa em si é cancelada ou lança uma exceção. Neste caso, trata de uma AggregateException exceção. A AggregateException.InnerExceptions propriedade contém detalhes sobre a exceção ou exceções.

  • O intervalo definido pelos millisecondsTimeout elapses. Neste caso, o thread atual retoma a execução e o método devolve false.

Aplica-se a

Wait()

Espera que a Task execução seja concluída.

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 InnerExceptions coleção contém um TaskCanceledException objeto.

-ou-

Foi lançada uma exceção durante a execução da tarefa. A InnerExceptions coleção contém informações sobre a exceção ou exceções.

Exemplos

O exemplo seguinte inicia uma tarefa que gera um milhão de inteiros aleatórios entre 0 e 100 e calcula a sua média. O exemplo utiliza o Wait método para garantir que a tarefa é concluída antes do término da aplicação. Caso contrário, por se tratar de uma aplicação de consola, o exemplo terminaria antes de a tarefa poder calcular e mostrar 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

Observações

Wait é um método de sincronização que faz com que a thread chamada espere até que a tarefa atual seja concluída. Se a tarefa atual não tiver iniciado a execução, o método Wait tenta remover a tarefa do escalonador e executá-la inline no thread atual. Se não conseguir fazê-lo, ou se a tarefa atual já tiver iniciado a execução, bloqueia o thread que chama até a tarefa ser concluída. Para mais informações, consulte Task.Wait e "Inlining" no blogue Parallel Programming with .NET.

Ver também

Aplica-se a