Export (0) Print
Expand All

Task.Wait Method (Int32, CancellationToken)

Waits for the Task to complete execution. The wait terminates if a timeout interval elapses or a cancellation token is canceled before the task completes.

Namespace:  System.Threading.Tasks
Assemblies:   System.Threading.Tasks (in System.Threading.Tasks.dll)
  mscorlib (in mscorlib.dll)

public bool Wait(
	int millisecondsTimeout,
	CancellationToken cancellationToken
)

Parameters

millisecondsTimeout
Type: System.Int32

The number of milliseconds to wait, or Infinite (-1) to wait indefinitely.

cancellationToken
Type: System.Threading.CancellationToken

A cancellation token to observe while waiting for the task to complete.

Return Value

Type: System.Boolean
true if the Task completed execution within the allotted time; otherwise, false.

ExceptionCondition
OperationCanceledException

The cancellationToken was canceled.

ObjectDisposedException

The Task has been disposed.

ArgumentOutOfRangeException

millisecondsTimeout is a negative number other than -1, which represents an infinite time-out.

AggregateException

The task was canceled. The AggregateException.InnerExceptions collection contains a TaskCanceledException object.

-or-

An exception was thrown during the execution of the task. The AggregateException.InnerExceptions collection contains information about the exception or exceptions.

Wait(Int32, CancellationToken) is a synchronization method that causes the calling thread to wait for the current task instance to complete until one of the following occurs:

  • The task completes successfully.

  • The task itself is canceled or throws an exception. In this case, you handle an AggregateException exception. The AggregateException.InnerExceptions property contains details about the exception or exceptions.

  • The cancellationToken cancellation token is canceled. In this case, the call to the Wait(Int32, CancellationToken) method throws an OperationCanceledException.

  • The interval defined by millisecondsTimeout elapses. In this case, the current thread resumes execution and the method returns false.

NoteNote

Canceling the cancellationToken cancellation token has no effect on the running task unless it has also been passed the cancellation token and is prepared to handle cancellation. Passing the cancellationToken object to this method simply allows the wait to be canceled based on some condition.

The following example calls the Wait(Int32, CancellationToken) method to provide both a timeout value and a cancellation token that can end the wait for a task's completion. A new thread is started and executes the CancelToken method, which pauses and then calls the CancellationTokenSource.Cancel method to cancel the cancellation tokens. A task is then launched and delays for 5 seconds. The Wait method is then called to wait for the task's completion and is provided both a brief timeout value and a cancellation token.

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

Note that the precise output from the example depends on whether the wait was canceled because of the cancellation token or because the timeout interval elapsed.

.NET Framework

Supported in: 4.6, 4.5, 4

.NET Framework Client Profile

Supported in: 4

Portable Class Library

Supported in: Portable Class Library

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8
Show:
© 2015 Microsoft