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
Problem
There is an older asynchronous pattern that uses methods named along with events named OperationAsync. You want to perform an operation using the older asynchronous pattern and OperationCompletedawait the result.
Tip
The and OperationAsync pattern is called the Event-based Asynchronous Pattern (EAP). You’re going to wrap those into a OperationCompletedTask-returning method that follows the Task-based Asynchronous Pattern (TAP).
Solution
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 string. The WebClient type defines DownloadStringAsync and DownloadStringCompleted. Using those, you can define a DownloadStringTaskAsync method, like this:
publicstaticTask<string>DownloadStringTaskAsync(thisWebClientclient,Uriaddress){vartcs=newTaskCompletionSource<string>();// The ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access