Home > Articles

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020