Home > Articles

  • Print
  • + Share This
This chapter is from the book

Item 29: Avoid Composing Synchronous and Asynchronous Methods

Declaring a method with the async modifier signals that this method may return before completing all its work. The returned object represents the state of that work: completed, faulted, or still pending. Use of an async method further indicates that any pending work may take long enough that callers are advised to await the result while doing other useful work.

Declaring a synchronous method asserts that when it completes, all of its post conditions will have been met. Regardless of the time the method takes to execute, it does all its work using the same resources as the caller. The caller blocks until completion.

Mixing these clear statements leads to poor API design and can produce bugs, including deadlock. The possibility of these outcomes leads to two important rules. First, don’t create synchronous methods that block waiting for asynchronous work to complete. Second, avoid async methods to offload long-running CPU-bound work.

Let’s investigate the first rule further. There are three reasons why composing synchronous code on top of asynchronous code causes problems: different exception semantics, possible deadlocks, and resource consumption.

Asynchronous tasks may cause multiple exceptions, so the Task class contains a list of exceptions that have been thrown. When you await a task, the first exception in that list is thrown, if this list includes any exceptions. However, when you call Task.Wait() or access Task.Result, the containing AggregateException is thrown for a faulted task. You must then catch the AggregateException and unwrap the exception that was thrown. Compare these two try/catch clauses:

public static async Task<int> ComputeUsageAsync()
{
try
{
var operand = await GetLeftOperandForIndex(19);
var operand2 = await GetRightOperandForIndex(23);
return operand + operand2;
}
catch (KeyNotFoundException e)
{
return 0;
}
}

public static int ComputeUsage()
{
try
{
var operand = GetLeftOperandForIndex(19).Result;
var operand2 = GetRightOperandForIndex(23).Result;
return operand + operand2;
}
catch (AggregateException e)
when (e.InnerExceptions.FirstOrDefault().GetType()
== typeof(KeyNotFoundException))
{
return 0;
}
}

Notice the difference in semantics for handling the exceptions. The version in which the task is awaited is much more readable than the version in which a blocking call is used. The awaited version catches the specific type of exception, whereas the blocking version catches an aggregate exception and must apply an exception filter to ensure that it catches the exception only when the first contained exception matches the sought exception types. The idioms needed for the blocking APIs are more complicated, and more difficult for other developers to understand.

Now let’s consider the second rule—specifically, how composing synchronous methods over asynchronous code can lead to deadlocks. Consider this code:

private static async Task SimulatedWorkAsync()
{
await Task.Delay(1000);
}

// This method can cause a deadlock in ASP.NET or GUI context.
public static void SyncOverAsyncDeadlock()
{
// Start the task.
var delayTask = SimulatedWorkAsync();
// Wait synchronously for the delay to complete.
delayTask.Wait();
}

Calling SyncOverAsyncDeadlock() works correctly in a console application, but it will deadlock in either a GUI or Web context. That’s because these different application types make use of different types of synchronization contexts (see Item 31). The SynchronizationContext for console applications contains multiple threads from the thread pool, whereas the SynchronizationContext for the GUI and ASP.NET contexts contains a single thread. The awaited task, which is started by SimulatedWorkAsync(), cannot continue because the only thread available is blocked waiting for the task to complete. Ideally, your APIs should be useful in as many application types as possible. Composing synchronous code on top of asynchronous APIs defeats that purpose. Instead of waiting synchronously for asynchronous work to finish, perform other work while awaiting the task to finish.

Notice that the preceding example used Task.Delay instead of Thread.Sleep to yield control and simulate a longer-running task. This approach is preferred because Thread.Sleep makes your application pay the cost of that thread’s resources for the entire time it is idle. You made that thread—keep it busy doing useful work. Task.Delay is asynchronous and will enable callers to compose asynchronous work while your task simulates longer-running tasks. This behavior can be useful in unit tests to ensure that your tasks finish asynchronously (see Item 27).

There is one common exception to the rule that you should not compose synchronous methods over asynchronous methods: with the Main() method in a console application. If the Main() method were asynchronous, it could return before all the work was complete, terminating the program. Thus, this method is the one location where synchronous methods should be preferred over asynchronous methods. Otherwise, it’s async all the way up. A proposal has been made to allow the Main() method to be asynchronous and handle that situation. There is also a NuGet package, AsyncEx, that supports an async main context.

You probably have synchronous APIs in your libraries today that can be updated to be asynchronous APIs. Removing your synchronous API would be a breaking change. I’ve just convinced you not to convert to an asynchronous API and redirect the synchronous method to block while calling the asynchronous method—but that doesn’t mean you’re stuck supporting only the synchronous API with no path forward. You can create an asynchronous API that mirrors the synchronous code, and support both. Those users who are ready for asynchronous work will use the async method, and the others can continue using the synchronous method. At some later date, you can deprecate the synchronous method. In fact, some developers are already beginning to make assumptions about libraries that support both synchronous and asynchronous versions of the same method: They assume the synchronous method is a legacy method, and the asynchronous method is the preferred method.

This observation suggests why an async API that wraps a synchronous CPU-bound operation is also a bad idea. If developers assume that the asynchronous method is preferred when both synchronous and asynchronous versions of the same method are available, they’ll naturally gravitate toward the asynchronous method. When that async method is simply a wrapper, you’ve misled them. Consider the following two methods:

public double ComputeValue()
{
// Do lots of work.
double finalAnswer = 0;
for (int i = 0; i < 10_000_000; i++)
finalAnswer += InterimCalculation(i);
return finalAnswer;
}

public Task<double> ComputeValueAsync()
{
return Task.Run(() => ComputeValue());
}

The synchronous version enables callers to decide whether they want to run that CPU-bound work synchronously versus asynchronously on another thread. The asynchronous method takes that choice away from them. Callers are forced to spin up a new thread or retrieve one from a pool, and then run this operation on that new thread. If this CPU-bound work is part of a larger operation, it may already be on a separate thread. Alternatively, it may be called from a console application, in which case running on a background thread just ties up more resources.

This is not to say there is no place for doing CPU-bound work on separate threads. Rather, the point is that CPU-bound work should be as large-grained as possible. The code that starts the background task should appear at the entry point to your application. Consider the Main() method to a console application, response handlers in a Web application, or UI handlers in a GUI application: These are the points in an application where CPU-bound work should be dispatched to other threads. Creating asynchronous methods over CPU-bound synchronous work in other locations merely misleads other developers.

The effects of offloading work using asynchronous methods begin to worm their way through your application as you compose more asynchronous methods on top of other asynchronous APIs. That’s exactly as it should be. You’ll keep adding ever more async methods in vertical slices up the call stack. If you are converting or extending an existing library, consider running asynchronous and synchronous versions of your API side by side. But only take this course when the work is asynchronous and you are offloading work to another resource. If you are adding asynchronous versions of CPU-bound methods, you are just misleading your users.

  • + Share This
  • 🔖 Save To Your Account