Chapter 7. Interop
Asynchronous, parallel, reactive—each has its place, but how well do they work together?
In this chapter, we’ll look at various interop scenarios where we will learn how to combine these different approaches. We’ll learn that they complement each other, rather than compete; there is very little friction at the boundaries where one approach meets another.
7.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 wish to perform an operation like this and OperationCompletedawait the result.
Tip
The and OperationAsync pattern is called the Event-based Asynchronous Pattern (EAP). We’re going to wrap those into a OperationCompletedTask-returning method that follows the Task-based Asynchronous Pattern (TAP).
Solution
You can create wrappers for asynchronous operations by using the TaskCompletionSource<TResult> type. This type controls a Task<TResult> and allows you to complete the task at the appropriate time.
The following example defines an extension method for WebClient that downloads a string. The WebClient type defines DownloadStringAsync and DownloadStringCompleted. Using those, we can define a DownloadStringTaskAsync method as such:
publicstaticTask<string>DownloadStringTaskAsync(thisWebClientclient,Uriaddress){vartcs=newTaskCompletionSource<string>();// The event handler will complete the task and unregister itself.DownloadStringCompletedEventHandler ...
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