Wait for a single Task in .NET C#: the Wait() method
February 28, 2014 1 Comment
Waiting for a single Task to finish is as easy as calling the Wait() method or one of its overloaded versions:
Wait(); Wait(CancellationToken); Wait(int); Wait(TimeSpan); Wait(int, CancellationToken);
In short from top to bottom:
- Wait until the Task completes, is cancelled or throws an exception
- Wait until the cancellation token is cancelled or the task completes, is cancelled or throws an exception
- Wait for ‘int’ amount of milliseconds to pass OR for the task to complete, be cancelled or throw an exception, whichever happens first
- Wait for ‘TimeSpan’ amount of time to pass OR for the task to complete, be cancelled or throw an exception, whichever happens first
- Wait for ‘int’ amount of milliseconds to pass, for the cancellation token to be cancelled, OR for the task to complete, be cancelled or throw an exception, whichever happens first
Example:
Construct the cancellation token:
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); CancellationToken cancellationToken = cancellationTokenSource.Token;
Start a task:
Task task = Task.Factory.StartNew(() =>
{
for (int i = 0; i < 10; i++)
{
cancellationToken.ThrowIfCancellationRequested();
Console.WriteLine(i);
cancellationToken.WaitHandle.WaitOne(1000);
}
}, cancellationToken);
We can then wait for the task to complete:
task.Wait();
If we are impatient then we specify a maximum amount of milliseconds for the task to complete otherwise it is abandoned:
task.Wait(2000);
The other overloads work in a similar manner.
View the list of posts on the Task Parallel Library here.
Pingback: Wait for a single Task in .NET C#: the Wait() method | D Says