Introducing the Task Parallel Library in Microsoft Visual C# 2010

  • 4/15/2010

Chapter 27 Quick Reference

To

Do this

Create a task and run it

Either use the StartNew method of a TaskFactory object to create and run the task in a single step:

Task task = taskFactory.StartNew(doWork());
...
private void doWork()
{
    // The task runs this code when it is started
    ...
}

Or create a new Task object that references a method to run and call the Start method:

Task task = new Task(doWork);
task.Start();

Wait for a task to finish

Call the Wait method of the Task object:

Task task = ...;
...
task.Wait();

Wait for several tasks to finish

Call the static WaitAll method of the Task class, and specify the tasks to wait for:

Task task1 = ...;
Task task2 = ...;
Task task3 = ...;
Task task4 = ...;
...
Task.WaitAll(task1, task2, task3, task4);

Specify a method to run in a new task when a task has completed

Call the ContinueWith method of the task, and specify the method as a continuation:

Task task = new Task(doWork);
task.ContinueWith(doMoreWork,
    TaskContinuationOptions.NotOnFaulted);

Return a value from a task

Use a Task<TResult> object to run a method, where the type parameter T specifies the type of the return value of the method. Use the Result property of the task to wait for the task to complete and return the value:

Task<int> calculateValueTask = new Task<int>(() =>
calculateValue(...));
calculateValueTask.Start(); // Invoke the calculateValue method
...
int calculatedData = calculateValueTask.Result; // Block until
calculateValueTask completes

Perform loop iterations and statement sequences by using parallel tasks

Use the Parallel.For and Parallel.ForEach methods to perform loop iterations by using tasks:

Parallel.For(0, 100, performLoopProcessing);
...
private void performLoopProcessing(int x)
{
    // Perform loop processing
}

Use the Parallel.Invoke method to perform concurrent method calls by using separate tasks:

Parallel.Invoke(
    doWork,
    doMoreWork,
    doYetMoreWork
);

Handle exceptions raised by one or more tasks

Catch the AggregateException exception. Use the Handle method to specify a method that can handle each exception in the AggregateException object. If the exception-handling method handles the exception, return true; otherwise, return false:

try
{
    Task task = Task.Factory.StartNew(...);
    ...
}
catch (AggregateException ae)
{
    ae.Handle(new Func<Exception, bool> (handleException));
}
...
private bool handleException(Exception e)
{
    if (e is TaskCanceledException)
    {
        ...
        return true;
    }
    else
    {
        return false;
    }
}

Support cancellation in a task

Implement cooperative cancellation by creating a CancellationTokenSource object and using a CancellationToken parameter in the method run by the task. In the task method, call the ThrowIfCancellationRequested method of the CancellationToken parameter to throw an OperationCanceledException exception and terminate the task:

private void generateGraphData(..., CancellationToken token)
{
    ...
    token.ThrowIfCancellationRequested();
    ...
}