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 OperationAsync along with events named OperationCompleted. You want to perform an operation using the older asynchronous pattern and await the result.

Tip

The OperationAsync and OperationCompleted 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).

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:

public static Task<string> DownloadStringTaskAsync(this WebClient client,
    Uri address)
{
  var tcs = new TaskCompletionSource<string>();

  // The ...

Get Concurrency in C# Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.