Information Technology Reference
In-Depth Information
It's important here because you are using the WebClient class's async
methods to create the task. The type parameter for the TaskCompletion-
Source is the type of result returned from the task.
The WebClient class uses the Event-based Asynchronous Pattern (EAP).
That means you register a handler for an event that will be raised when an
asynchronous operation completes. startDownload() stores the task com-
pletion information in the TaskCompletionSource when that event is
raised. The TaskSheduler picks up the task and then the download is
started. The method returns the Task object embedded inside the
Ta s k C o m p l e t i o n S o u r c e s o t h a t t h e e v e n t r e s u l t s c a n b e p r o c e s s e d o n c e t h e
task completes.
After this bit of work, the Web download occurs asynchronously on another
thread. When the download completes, the DownloadDataCompleted
event is raised. The event handler will set the completion status for the
Ta s k C o m p l e t i o n S o u r c e .
T h a t
s i g n a l s
t h e
Ta s k
e m b e d d e d
i n
t h e
TaskCompletionSource that it has finished.
Now, the task will invoke ContinueWith(), which will report the results
for that download. It takes a bit of unwinding, but after you've unwound
it once, the pattern isn't that hard to understand.
The sample shown above is the correct idiom to use when the underlying
source uses the Event-based Asynchronous Pattern. Other areas of the
.NET library will use the Asynchronous Programming Model (APM) pat-
tern. In that pattern, for some operation Foo you'll call BeginFoo(), which
will return an IAsyncResult. Once the operation has completed, you'll call
EndFoo(), passing in the IAsyncResult. You can use the Task<TResult>
.Factory.FromAsync() method to implement this pattern using the Paral-
lel Task Library. The underlying idiom will be similar to the version I've
shown for downloading Web data. The difference would be where you cre-
ate the task you'd provide a different set of delegates to match the async
method being used.
The Parallel Task Library provides a series of methods that enable work-
ing with I/O bound operations as well as CPU bound partitions of work.
Using the Task class, you can support a variety of asynchronous patterns
that work with I/O bound operations, or those that are a mixture of I/O
and CPU bound operations. Parallel tasks are still not easy, but the Paral-
lel Task Library and PLINQ provide better language level support for asyn-
chronous programming than previous libraries had. It will continue to be
 
Search WWH ::




Custom Search