次の方法で共有


Task.Wait メソッド

定義

Taskの実行が完了するまで待機します。

オーバーロード

名前 説明
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

タスクの完了を待機している間に観察する CancellationToken

戻り値

true 割り当てられた時間内に実行が完了した Task 場合は ɴ。それ以外の場合は false

例外

Taskが取り消されました

-又は-

Taskの実行中に例外がスローされました。

timeout は、無限タイムアウトを表す -1 ミリ秒以外の負の数です。

-又は-

タイムアウトが MaxValueを超えています。

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

パラメーター

millisecondsTimeout
Int32

待機するミリ秒数、または無期限に待機する Infinite (-1)。

cancellationToken
CancellationToken

タスクの完了を待機している間に観察するキャンセル トークン。

戻り値

true 割り当てられた時間内に実行が完了した Task 場合は ɴ。それ以外の場合は false

例外

cancellationToken は取り消されました。

Taskが破棄されました。

millisecondsTimeout は-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

パラメーター

timeout
TimeSpan

待機するミリ秒数を表す TimeSpan 、または無期限に待機する -1 ミリ秒を表す TimeSpan

戻り値

true 割り当てられた時間内に実行が完了した Task 場合は ɴ。それ以外の場合は false

例外

Taskが破棄されました。

timeout は、無限タイムアウトを表す、-1 ミリ秒以外の負の数です。

-又は-

timeoutInt32.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(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 メソッドを呼び出してトークン ソースのキャンセル トークンのいずれかを取り消した後、5 秒間遅延します。 タスク自体はキャンセル トークンを渡されておらず、取り消し可能ではないことに注意してください。 アプリケーション スレッドはタスクの 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
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()

ソース:
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 までの 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)

ソース:
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

パラメーター

millisecondsTimeout
Int32

待機するミリ秒数、または無期限に待機する Infinite (-1)。

戻り値

true 割り当てられた時間内に実行が完了した Task 場合は ɴ。それ以外の場合は false

例外

Taskが破棄されました。

millisecondsTimeout は-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を返します。

適用対象