Waiting for one in a group of Tasks to complete in .NET C#
March 5, 2014 Leave a comment
You can use the static WaitAny() method to wait for one of many tasks to complete. The method blocks until one of the tasks has finished. It returns the array index of the task that has finished first.
WaitAny() has a number of overloaded versions which follow the same pattern as the Wait() method we saw in this post. If you use one of the overloaded methods then an array index of -1 means that the time period has expired or the cancellation token has been cancelled before any of the tasks could complete.
Example:
Build the cancellation token:
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); CancellationToken cancellationToken = cancellationTokenSource.Token;
Construct two – or more- tasks:
Task taskOne = Task.Factory.StartNew(() =>
{
for (int i = 0; i < 10; i++)
{
cancellationToken.ThrowIfCancellationRequested();
Console.WriteLine(i);
cancellationToken.WaitHandle.WaitOne(1000);
}
Console.WriteLine("Task 1 complete");
}, cancellationToken);
Task taskTwo = Task.Factory.StartNew(() =>
{
for (int i = 0; i < 5; i++)
{
cancellationToken.ThrowIfCancellationRequested();
Console.WriteLine(i);
cancellationToken.WaitHandle.WaitOne(500);
}
Console.WriteLine("Task 2 complete");
}, cancellationToken);
Wait for the first one:
int arrayIndex = Task.WaitAny(taskOne, taskTwo);
Note that a task provided to the WaitAny method is considered “complete” if either of the following is true:
- The task finishes its work
- The task is cancelled
- The task has thrown an exception
If one of the tasks throws an exception then WaitAny will also throw one.
View the list of posts on the Task Parallel Library here.