Chapter 8. Interop
Asynchronous, parallel, reactive—each of these has its place, but how well do they work together?
In this chapter, we’ll look at various interop scenarios where you’ll learn how to combine these different approaches. You’ll learn that they complement each other, rather than compete; there’s very little friction at the boundaries where one approach meets another.
8.1 Async Wrappers for “Async” Methods with “Completed” Events
There is an older asynchronous pattern that uses methods named
along with events named
. You want to perform an operation using the older asynchronous pattern and
await the result.
pattern is called the Event-based Asynchronous Pattern (EAP). You’re going to wrap those into a
Task-returning method that follows the Task-based Asynchronous Pattern (TAP).
By using the
TaskCompletionSource<TResult> type, you can create wrappers for asynchronous operations. The
TaskCompletionSource<TResult> type controls a
Task<TResult> and enables you to complete the task at the appropriate time.
This example defines an extension method for
WebClient that downloads a
WebClient type defines
DownloadStringCompleted. Using those, you can define a
DownloadStringTaskAsync method, like this:
// The ...