Information Technology Reference
In-Depth Information
The code shown above is not truly asynchronous. It's making use of mul-
tiple threads to perform some work in parallel, but the surrounding pro-
gram will wait for all the Web requests to finish before continuing with
other work. The Parallel Task Library provides other primitives to imple-
ment the async pattern. One very common pattern is to begin a number
of I/O bound tasks and perform some action on those results. Ideally, I'd
like to write something like:
urls.RunAsync(
url => startDownload(url),
task => finishDownload(task.AsyncState.ToString(),
task.Result));
This would use the startDownload() method to begin downloading each
URL. As each download finishes, finishDownload() would be called. Once
all the downloads have finished, RunAsync() would finish. There is a rea-
sonable amount of work using the Parallel Task Library to accomplish this,
so let's examine it closely. The best place to begin is the RunAsync method
itself:
public static void RunAsync<T, TResult>(
this IEnumerable <T> taskParms,
Func <T, Task <TResult>> taskStarter,
Action < Task <TResult>> taskFinisher)
{
taskParms.Select(parm => taskStarter(parm)).
AsParallel().
ForAll(t => t.ContinueWith(t2 => taskFinisher(t2)));
}
This method creates a task per input parameter. The Select() method
returns the sequence of tasks. Next, you need to opt into parallel process-
ing of the results, by using AsParallel(). For every single task, you'll want
to call the post processing method for every task. The Task<T> class rep-
resents a (possibly parallel) task and contains properties to report on the
input and output values from the task. One of the methods of Task<T> is
ContinueWith(). It will be called as the task finishes and allows you to per-
form any processing after the task has finished running. In the RunAsync
method, it calls the taskFinisher, giving the Task object as the parameter.
That enables the caller to perform any processing as the task finishes.
ForAll() performs the inverted enumeration, so that it blocks until all tasks
have completed.
 
Search WWH ::




Custom Search