This is a mirror of official site: http://jasper-net.blogspot.com/

Cancelling Tasks Started with Parallel.Invoke

| Thursday, July 5, 2012
Cancelling Parallel.Invoke Tasks
Cancellation of tasks started using Parallel.Invoke uses the same cancellation token approach as when cancelling other parallel operations. Before you start the parallel execution, you must create a CancellationTokenSource object, from which you can request a CancellationToken. This token is passed to the Parallel.Invoke method's first parameter, with the Action array becoming the second parameter. However, the token cannot be provided directly as when creating cancellable Task objects. Instead, you must instantiate a ParallelOptions object and set its CancellationToken property to the generated token.

With the cancellation token provided, you can call its Cancel method from within any of the Action delegates. To avoid problems with early termination, cancelling the tasks does not immediately stop their execution. Any tasks from the array that have not already begun executing will not be started. Any tasks that have already started will continue to run until they complete normally or throw an exception. For particularly long-running tasks, you may also check the cancellation token source's IsCancellationRequested property. If this is true, you can gracefully exit from a task early to improve performance.

When the tasks are cancelled, an OperationCanceledException is thrown, as it would be when you cancel tasks manually. You should generally catch this exception to ensure that it does not cause your software to exit abnormally. Other exceptions will be wrapped in an AggregateException and should be handled appropriately.
To demonstrate cancellation, first we need a cancellation token source that is visible to the entire program. Add the following declaration to the class, outside of any member.
static CancellationTokenSource _tokenSource;

We'll also add a new method that cancels the operation. This will be called by one of the Action delegates.

static void CancellingTask()
{
    Console.WriteLine("Cancelling {0}", Task.CurrentId);
    _tokenSource.Cancel();
}

Read more: BlackWasp
QR: Inline image 1

Posted via email from Jasper-net

0 comments: