Task.Wait 方法

定义

等待 Task 完成执行过程。

重载

Wait()

等待 Task 完成执行过程。

Wait(Int32)

等待 Task 在指定的毫秒数内完成执行。

Wait(CancellationToken)

等待 Task 完成执行过程。 如果在任务完成之前取消标记已取消,等待将终止。

Wait(TimeSpan)

等待 Task 在指定的时间间隔内完成执行。

Wait(Int32, CancellationToken)

等待 Task 完成执行过程。 如果在任务完成之前超时间隔结束或取消标记已取消,等待将终止。

Wait(TimeSpan, CancellationToken)

等待 Task 完成执行过程。

Wait()

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

等待 Task 完成执行过程。

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

例外

已释放了 Task

已取消任务。 InnerExceptions 集合包含 TaskCanceledException 对象。

- 或 -

执行任务期间引发了一个异常。 InnerExceptions 集合包含一个或多个异常的相关信息。

示例

以下示例启动一个任务,该任务生成 0 到 100 之间的 100 万个随机整数,并计算其平均值。 该示例使用 Wait 方法确保任务在应用程序终止之前完成。 否则,由于这是一个控制台应用程序,因此该示例将在任务可以计算和显示平均值之前终止。

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

注解

Wait 是一种同步方法,它会导致调用线程等待当前任务完成。 如果当前任务尚未开始执行,Wait 方法会尝试从计划程序中删除该任务,并在当前线程上内联执行该任务。 如果它无法执行此操作,或者如果当前任务已经开始执行,它会阻止调用线程,直到任务完成。 有关详细信息,请参阅使用 .NET 并行编程博客中的 Task.Wait 和“内联”。

另请参阅

适用于

Wait(Int32)

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

等待 Task 在指定的毫秒数内完成执行。

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

参数

millisecondsTimeout
Int32

等待的毫秒数,或为 Infinite (-1),表示无限期等待。

返回

如果在分配的时间内 true 完成执行,则为 Task;否则为 false

例外

已释放了 Task

millisecondsTimeout 是一个非 -1 的负数,而 -1 表示无限期超时。

已取消任务。 InnerExceptions 集合包含 TaskCanceledException 对象。

- 或 -

执行任务期间引发了一个异常。 InnerExceptions 集合包含一个或多个异常的相关信息。

示例

以下示例启动一个任务,该任务生成 0 到 100 之间的 500 万个随机整数,并计算其平均值。 该示例使用 Wait(Int32) 方法等待应用程序在 150 毫秒内完成。 如果应用程序正常完成,则任务会显示它生成的随机数之和和平均值。 如果超时间隔已过,则本示例在终止前显示一条消息。

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.

注解

Wait(Int32) 是一种同步方法,它会导致调用线程等待当前任务实例完成,直到发生以下任一情况:

  • 任务成功完成。

  • 任务本身被取消或引发异常。 在这种情况下,你将处理异常 AggregateException 。 属性 AggregateException.InnerExceptions 包含有关异常的详细信息。

  • millisecondsTimeout 已用定义的间隔。 在这种情况下,当前线程继续执行,方法返回 false

适用于

Wait(CancellationToken)

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

等待 Task 完成执行过程。 如果在任务完成之前取消标记已取消,等待将终止。

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)

参数

cancellationToken
CancellationToken

等待任务完成期间要观察的取消标记。

例外

已取消 cancellationToken

已释放该任务。

已取消任务。 InnerExceptions 集合包含 TaskCanceledException 对象。

- 或 -

执行任务期间引发了一个异常。 InnerExceptions 集合包含一个或多个异常的相关信息。

示例

以下示例演示了取消令牌的简单用法,以取消等待任务完成。 启动任务,调用 CancellationTokenSource.Cancel 方法来取消任何令牌源的取消令牌,然后延迟 5 秒。 请注意,任务本身尚未传递取消令牌,并且不可取消。 应用程序线程调用任务的 Task.Wait 方法来等待任务完成,但在取消令牌取消并 OperationCanceledException 引发 后,等待将取消。 异常处理程序报告异常,然后休眠六秒钟。 如示例输出所示,延迟允许任务在 状态中 RanToCompletion 完成。

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

注解

方法 Wait(CancellationToken) 创建可取消等待;也就是说,它会导致当前线程等待,直到发生以下任一情况:

注意

取消 cancellationToken 取消令牌不会影响正在运行的任务,除非它已传递取消令牌并准备处理取消。 将 cancellationToken 对象传递给此方法只是允许取消等待。

适用于

Wait(TimeSpan)

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

等待 Task 在指定的时间间隔内完成执行。

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

参数

timeout
TimeSpan

表示等待毫秒数的 TimeSpan,或表示 -1 毫秒(无限期等待)的 TimeSpan

返回

如果在分配的时间内 true 完成执行,则为 Task;否则为 false

例外

已释放了 Task

timeout 为 -1 毫秒以外的负数,表示无限期超时。

- 或 -

timeout 大于 Int32.MaxValue

已取消任务。 InnerExceptions 集合包含 TaskCanceledException 对象。

- 或 -

执行任务期间引发了一个异常。 InnerExceptions 集合包含一个或多个异常的相关信息。

示例

以下示例启动一个任务,该任务生成 0 到 100 之间的 500 万个随机整数,并计算其平均值。 该示例使用 Wait(TimeSpan) 方法等待应用程序在 150 毫秒内完成。 如果应用程序正常完成,则任务会显示它生成的随机数之和和平均值。 如果超时间隔已过,则本示例在终止前显示一条消息。

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.

注解

Wait(TimeSpan) 是一种同步方法,它会导致调用线程等待当前任务实例完成,直到发生以下任一情况:

  • 任务成功完成。

  • 任务本身被取消或引发异常。 在这种情况下,你将处理异常 AggregateException 。 属性 AggregateException.InnerExceptions 包含有关异常的详细信息。

  • timeout 已用定义的间隔。 在这种情况下,当前线程继续执行,方法返回 false

适用于

Wait(Int32, CancellationToken)

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

等待 Task 完成执行过程。 如果在任务完成之前超时间隔结束或取消标记已取消,等待将终止。

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

参数

millisecondsTimeout
Int32

等待的毫秒数,或为 Infinite (-1),表示无限期等待。

cancellationToken
CancellationToken

等待任务完成期间要观察的取消标记。

返回

如果在分配的时间内 true 完成执行,则为 Task;否则为 false

例外

已取消 cancellationToken

已释放了 Task

millisecondsTimeout 是一个非 -1 的负数,而 -1 表示无限期超时。

已取消任务。 InnerExceptions 集合包含 TaskCanceledException 对象。

- 或 -

执行任务期间引发了一个异常。 InnerExceptions 集合包含一个或多个异常的相关信息。

示例

以下示例调用 Wait(Int32, CancellationToken) 方法以提供超时值和取消标记,以便结束任务完成的等待。 启动新线程并执行 CancelToken 方法,该方法暂停,然后调用 CancellationTokenSource.Cancel 方法来取消取消令牌。 然后启动任务并延迟 5 秒。 Wait然后调用 方法以等待任务完成,并同时提供一个简短的超时值和一个取消标记。

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

请注意,此示例的精确输出取决于等待是因为取消标记还是因为超时间隔而取消。

注解

Wait(Int32, CancellationToken) 是一种同步方法,它会导致调用线程等待当前任务实例完成,直到发生以下情况之一:

注意

取消 cancellationToken 取消令牌不会影响正在运行的任务,除非它也已传递取消令牌并准备处理取消。 将 cancellationToken 对象传递给此方法只是允许根据某种条件取消等待。

适用于

Wait(TimeSpan, CancellationToken)

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

等待 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

参数

timeout
TimeSpan

等待或 InfiniteTimeSpan 无限期等待的时间

cancellationToken
CancellationToken

等待 CancellationToken 任务完成时要观察的 。

返回

如果在分配的时间内 true 完成执行,则为 Task;否则为 false

例外

Task已取消

\- 或 -

在执行 Task期间引发了异常。

timeout 是一个负数,而不是 -1 毫秒,表示无限超时

\- 或 -

超时大于 MaxValue

已取消 cancellationToken

适用于