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.
Assemblies: System.Threading.Tasks (in System.Threading.Tasks.dll)
mscorlib (in mscorlib.dll)
public: bool Wait( int millisecondsTimeout, CancellationToken cancellationToken )
- Type: System::Int32
The number of milliseconds to wait, or Infinite (-1) to wait indefinitely.
- Type: System.Threading::CancellationToken
A cancellation token to observe while waiting for the task to complete.
The cancellationToken was canceled.
The Task has been disposed.
millisecondsTimeout is a negative number other than -1, which represents an infinite time-out.
An exception was thrown during the execution of the task. The AggregateException::InnerExceptions collection contains information about the exception or exceptions.
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 method throws an OperationCanceledException.
The interval defined by millisecondsTimeout elapses. In this case, the current thread resumes execution and the method returns false.
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 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.
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.