Task.Wait 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
等待 Task 完成执行过程。
重载
Wait(TimeSpan) |
等待 Task 在指定的时间间隔内完成执行。 |
Wait(Int32, CancellationToken) |
等待 Task 完成执行过程。 如果在任务完成之前超时间隔结束或取消标记已取消,等待将终止。 |
Wait(CancellationToken) |
等待 Task 完成执行过程。 如果在任务完成之前取消标记已取消,等待将终止。 |
Wait(TimeSpan, CancellationToken) |
等待 Task 完成执行过程。 |
Wait() |
等待 Task 完成执行过程。 |
Wait(Int32) |
等待 Task 在指定的毫秒数内完成执行。 |
Wait(TimeSpan)
等待 Task 在指定的时间间隔内完成执行。
public:
bool Wait(TimeSpan timeout);
public bool Wait (TimeSpan timeout);
member this.Wait : TimeSpan -> bool
Public Function Wait (timeout As TimeSpan) As Boolean
参数
返回
如果在分配的时间内 true
完成执行,则为 Task;否则为 false
。
例外
已释放了 Task。
已取消任务。 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.
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)
等待 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
参数
- 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...
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) 是一种同步方法,它导致调用线程等待当前任务实例完成,直到发生以下情况之一:
任务成功完成。
任务本身已取消或引发异常。 在这种情况下,你将处理异常 AggregateException 。 该 AggregateException.InnerExceptions 属性包含有关异常或异常的详细信息。
取消
cancellationToken
标记。 在这种情况下,对方法的 Wait(Int32, CancellationToken) 调用将引发一个 OperationCanceledException。由
millisecondsTimeout
用时定义的间隔。 在这种情况下,当前线程将恢复执行,并且该方法返回false
。
备注
取消 cancellationToken
取消令牌对正在运行的任务没有影响,除非它也已通过取消令牌,并且已准备好处理取消。 将 cancellationToken
对象传递给此方法只是允许根据某些条件取消等待。
适用于
Wait(CancellationToken)
等待 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 该方法取消任何令牌源的取消令牌,然后延迟五秒。 请注意,任务本身尚未传递取消令牌,并且不可取消。 应用程序线程调用任务的方法来等待任务 Task.Wait 完成,但取消令牌取消并引发取消 OperationCanceledException 后,将取消等待。 异常处理程序报告异常,然后休眠 6 秒。 如示例的输出所示,延迟允许任务在状态中 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
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) 创建可取消的等待;也就是说,它会导致当前线程等待,直到发生以下情况之一:
任务完成。
取消标记。 在这种情况下,对方法的 Wait(CancellationToken) 调用将引发一个 OperationCanceledException。
备注
取消 cancellationToken
取消令牌对正在运行的任务没有影响,除非它也已通过取消令牌,并且已准备好处理取消。 将 cancellationToken
对象传递给此方法只是允许取消等待。
适用于
Wait(TimeSpan, CancellationToken)
等待 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
等待任务完成时观察的 A CancellationToken 。
返回
如果在分配的时间内 true
完成执行,则为 Task;否则为 false
。
例外
已取消 cancellationToken
。
适用于
Wait()
等待 Task 完成执行过程。
public:
void Wait();
public void Wait ();
member this.Wait : unit -> unit
Public Sub Wait ()
例外
已释放了 Task。
已取消任务。 InnerExceptions 集合包含 TaskCanceledException 对象。
- 或 - 执行任务期间引发了一个异常。 InnerExceptions 集合包含一个或多个异常的相关信息。
示例
以下示例启动一个任务,该任务在 0 到 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
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)
等待 Task 在指定的毫秒数内完成执行。
public:
bool Wait(int millisecondsTimeout);
public bool Wait (int millisecondsTimeout);
member this.Wait : int -> bool
Public Function Wait (millisecondsTimeout As Integer) As Boolean
参数
返回
如果在分配的时间内 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.
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
。