Task.Wait 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
等待 Task 執行完成。
多載
| 名稱 | Description |
|---|---|
| Wait(TimeSpan, CancellationToken) |
等待 Task 執行完成。 |
| Wait(Int32, CancellationToken) |
等待 Task 執行完成。 若逾時間隔過或任務完成前取消標記被取消,等待即告終止。 |
| Wait(TimeSpan) |
等待在 Task 指定時間內完成執行。 |
| Wait(CancellationToken) |
等待 Task 執行完成。 若任務完成前取消標記被取消,等待即終止。 |
| Wait() |
等待 Task 執行完成。 |
| Wait(Int32) |
等待在 Task 指定毫秒內完成執行。 |
Wait(TimeSpan, CancellationToken)
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- 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
A CancellationToken 在等待任務完成時觀察。
傳回
true若在指定時間內完成Task執行;否則,。 false
例外狀況
已取消 cancellationToken。
適用於
Wait(Int32, CancellationToken)
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- 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
參數
- 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) 是一種同步方法,會讓呼叫執行緒等待目前任務實例完成,直到以下其中一項發生:
任務順利完成。
任務本身會被取消或拋出例外。 在這種情況下,你處理的是 AggregateException 例外。 AggregateException.InnerExceptions該屬性包含關於例外或例外的詳細資訊。
cancellationToken取消令牌已取消。 此時,呼叫 Wait(Int32, CancellationToken) 該方法會拋出一個 OperationCanceledException。由
millisecondsTimeout經過點數定義的區間。 此時,當前執行緒會恢復執行,而該方法返回false。
備註
取消 cancellationToken 取消標記對執行任務沒有影響,除非任務同時被傳遞取消標記並準備好處理取消。 將物件傳遞 cancellationToken 給此方法,僅允許基於某些條件取消等待。
適用於
Wait(TimeSpan)
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- 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
參數
傳回
true若在指定時間內完成Task執行;否則,。 false
例外狀況
這些 Task 已經被處理掉了。
任務被取消。 該 InnerExceptions 收藏包含一件 TaskCanceledException 物件。
-或-
執行任務時會提出例外。 該 InnerExceptions 收藏包含關於例外或例外的資訊。
範例
以下範例啟動一項任務,產生五百萬個介於0到100之間的隨機整數,並計算其平均值。 範例中使用了 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(CancellationToken)
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- 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 該方法取消任何標記來源的取消標記,然後延遲五秒。 請注意,任務本身尚未被傳遞取消標記,且無法取消。 應用程式執行緒會呼叫任務 Task.Wait 的方法來等待任務完成,但一旦取消標記被取消並拋出 an 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) 方法會產生可取消的等待;也就是說,它會讓目前執行緒等待,直到以下其中一項發生:
任務完成。
取消令牌已取消。 此時,呼叫 Wait(CancellationToken) 該方法會拋出一個 OperationCanceledException。
備註
取消 cancellationToken 取消標記對執行任務沒有影響,除非任務同時被傳遞取消標記並準備好處理取消。 將物件傳遞 cancellationToken 給此方法,僅允許取消等待。
適用於
Wait()
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
等待 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
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 是一種同步方法,會讓呼叫執行緒等待當前任務完成。 如果目前的任務尚未開始執行,等待方法會嘗試將該任務從排程器中移除,並在目前執行緒中內嵌執行。 若無法執行,或當前任務已開始執行,則會阻塞呼叫執行緒直到任務完成。 更多資訊請參閱 Parallel Programming with .NET 部落格中的 Task.Wait 與「Inlineing」。
另請參閱
適用於
Wait(Int32)
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- Task.cs
- 來源:
- 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
參數
傳回
true若在指定時間內完成Task執行;否則,。 false
例外狀況
這些 Task 已經被處理掉了。
millisecondsTimeout 是除 -1 以外的負數,而 -1 代表無限次超時。
任務被取消。 該 InnerExceptions 收藏包含一件 TaskCanceledException 物件。
-或-
執行任務時會提出例外。 該 InnerExceptions 收藏包含關於例外或例外的資訊。
範例
以下範例啟動一項任務,產生五百萬個介於0到100之間的隨機整數,並計算其平均值。 範例中使用了 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。