## Wait(TimeSpan, CancellationToken)

``````public:
``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

cancellationToken
CancellationToken

Boolean

#### 例外

-或-

`timeout` 是除 -1 毫秒以外的负数，表示无限超时

-或-

timeout 大于 MaxValue

## Wait()

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

- 或 -

### 示例

``````using System;

public class Example
{
public static void Main()
{
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

let t =
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 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)

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

Boolean

#### 例外

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

- 或 -

### 示例

``````using System;

public class Example
{
public static void Main()
{
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

let t =
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 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)

``````public:
``public void Wait (System.Threading.CancellationToken cancellationToken);``
``member this.Wait : System.Threading.CancellationToken -> unit``
``Public Sub Wait (cancellationToken As CancellationToken)``

#### 参数

cancellationToken
CancellationToken

- 或 -

### 示例

``````using System;

public class Example
{
public static void Main()
{
CancellationTokenSource ts = new CancellationTokenSource();

ts.Cancel();
});
try {
t.Wait(ts.Token);
}
catch (OperationCanceledException e) {
Console.WriteLine("{0}: The wait has been canceled. Task status: {1:G}",
e.GetType().Name, t.Status);
Console.WriteLine("After sleeping, the task status:  {0:G}", t.Status);
}
ts.Dispose();
}
}
// The example displays output like the following:
//    Calling Cancel...
//    OperationCanceledException: The wait has been canceled. Task status: Running
//    After sleeping, the task status:  RanToCompletion
``````
``````open System

let ts = new CancellationTokenSource()

let t =
printfn "Calling Cancel..."
ts.Cancel()

try
t.Wait ts.Token

with :? OperationCanceledException as e ->
printfn \$"{e.GetType().Name}: The wait has been canceled. Task status: {t.Status:G}"
printfn \$"After sleeping, the task status:  {t.Status:G}"

ts.Dispose()

// The example displays output like the following:
//    Calling Cancel...
//    OperationCanceledException: The wait has been canceled. Task status: Running
//    After sleeping, the task status:  RanToCompletion
``````
``````Imports System.Threading

Module Example
Public Sub Main()
Dim ts As New CancellationTokenSource()

Console.WriteLine("Calling Cancel...")
ts.Cancel()
End Sub)
Try
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)
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:
'    Calling Cancel...
'    OperationCanceledException: The wait has been canceled. Task status: Running
'    After sleeping, the task status:  RanToCompletion
``````

## Wait(TimeSpan)

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

Boolean

#### 例外

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

- 或 -

`timeout` 大于 Int32.MaxValue

- 或 -

### 示例

``````using System;

public class Example
{
public static void Main()
{
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

let t =
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 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)

``````public:
``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

cancellationToken
CancellationToken

Boolean

#### 例外

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

- 或 -

### 示例

``````using System;

public class Example
{
public static void Main()
{
CancellationTokenSource ts = new CancellationTokenSource();

});
try {
bool result = t.Wait(1510, ts.Token);
Console.WriteLine("Wait completed normally: {0}", result);
}
catch (OperationCanceledException e) {
Console.WriteLine("{0}: The wait has been canceled. Task status: {1:G}",
e.GetType().Name, t.Status);
Console.WriteLine("After sleeping, the task status:  {0:G}", t.Status);
ts.Dispose();
}
}

private static void CancelToken(Object obj)
{
Console.WriteLine("Canceling the cancellation token from thread {0}...",
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:
//    Canceling the cancellation token from thread 3...
//    OperationCanceledException: The wait has been canceled. Task status: Running
//    After sleeping, the task status:  RanToCompletion
// The example displays output like the following if the wait is canceled by
// the timeout interval expiring:
//    Wait completed normally: False
//    Canceling the cancellation token from thread 3...
``````
``````open System

let cancelToken (obj: obj) =

match obj with
| :? CancellationTokenSource as source -> source.Cancel()
| _ -> ()

let ts = new CancellationTokenSource()

let t =

try
let result = t.Wait(1510, ts.Token)
printfn \$"Wait completed normally: {result}"

with :? OperationCanceledException as e ->
printfn \$"{e.GetType().Name}: The wait has been canceled. Task status: {t.Status:G}"
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:
//    Canceling the cancellation token from thread 3...
//    OperationCanceledException: The wait has been canceled. Task status: Running
//    After sleeping, the task status:  RanToCompletion
// The example displays output like the following if the wait is canceled by
// the timeout interval expiring:
//    Wait completed normally: False
//    Canceling the cancellation token from thread 3...
``````
``````Imports System.Threading

Module Example
Public Sub Main()
Dim ts As New CancellationTokenSource()

End Sub)
Try
Dim result As Boolean = t.Wait(1510, ts.Token)
Console.WriteLine("Wait completed normally: {0}", result)
Catch e As OperationCanceledException
Console.WriteLine("{0}: The wait has been canceled. Task status: {1:G}",
e.GetType().Name, t.Status)
Console.WriteLine("After sleeping, the task status:  {0:G}", t.Status)
ts.Dispose()
End Try
End Sub

Private Sub CancelToken(obj As Object)
Console.WriteLine("Canceling the cancellation token from thread {0}...",

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:
'    Canceling the cancellation token from thread 3...
'    OperationCanceledException: The wait has been canceled. Task status: Running
'    After sleeping, the task status:  RanToCompletion
' The example displays output like the following if the wait is canceled by
' the timeout interval expiring:
'    Wait completed normally: False
'    Canceling the cancellation token from thread 3...
``````

### 注解

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