Visual Studio 2012 introduces a simplified approach, async programming, that leverages asynchronous support in the .NET Framework 4.5 and the Windows Runtime. The compiler does the difficult work that the developer used to do, and your application retains a logical structure that resembles synchronous code. As a result, you get all the advantages of asynchronous programming with a fraction of the effort.
As developers we can avoid performance bottlenecks and enhance the overall responsiveness of our application by using asynchronous programming. However, traditional techniques for writing asynchronous applications can be complicated, making them difficult to write, debug, and maintain.
This topic contains the following sections.
- Async Improves Responsiveness
- Async Methods Are Easier to Write
- What Happens in an Async Method
- Complete Example
This topic provides an overview of when and how to use async programming and includes links to support topics that contain details and examples.
Async Improves Responsiveness
Asynchrony is essential for activities that are potentially blocking, such as when your application accesses the web. Access to a web resource sometimes is slow or delayed. If such an activity is blocked within a synchronous process, the entire application must wait. In an asynchronous process, the application can continue with other work that doesn’t depend on the web resource until the potentially blocking task finishes.
The following table shows typical areas where asynchronous programming improves responsiveness. The listed APIs from the .NET Framework 4.5 and the Windows Runtime contain methods that support async programming.
|Application area||Supporting APIs that contain async methods|
|Web access||HttpClient, SyndicationClient|
|Working with files||StorageFile, StreamWriter, StreamReader, XmlReader|
|Working with images||MediaCapture, BitmapEncoder, BitmapDecoder|
Asynchrony proves especially valuable for applications that access the UI thread because all UI-related activity usually shares one thread. If any process is blocked in a synchronous application, all are blocked. Your application stops responding, and you might conclude that it has failed when instead it’s just waiting.
When you use asynchronous methods, the application continues to respond to the UI. You can resize or minimize a window, for example, or you can close the application if you don’t want to wait for it to finish.
The async-based approach adds the equivalent of an automatic transmission to the list of options that you can choose from when designing asynchronous operations. That is, you get all the benefits of traditional asynchronous programming but with much less effort from the developer.
Async Methods Are Easier to Write
The Async and Await keywords in Visual Basic and the async and await keywords in C# are the heart of async programming. By using those two keywords, you can use resources in the .NET Framework or the Windows Runtime to create an asynchronous method almost as easily as you create a synchronous method. Asynchronous methods that you define by using async and await are referred to as async methods.
What Happens in an Async Method
The numbers in the diagram correspond to the following steps.
- An event handler calls and awaits the AccessTheWebAsync async method.
- AccessTheWebAsync creates an HttpClientinstance and calls the GetStringAsync asynchronous method to download the contents of a website as a string.
- Something happens in GetStringAsync that suspends its progress. Perhaps it must wait for a website to download or some other blocking activity. To avoid blocking resources, GetStringAsync yields control to its caller, AccessTheWebAsync.
GetStringAsync returns a Task where TResult is a string, and AccessTheWebAsync assigns the task to the getStringTask variable. The task represents the ongoing process for the call to GetStringAsync, with a commitment to produce an actual string value when the work is complete.
- Because getStringTask hasn’t been awaited yet, AccessTheWebAsync can continue with other work that doesn’t depend on the final result from GetStringAsync. That work is represented by a call to the synchronous method DoIndependentWork.
- DoIndependentWork is a synchronous method that does its work and returns to its caller.
- AccessTheWebAsync has run out of work that it can do without a result from getStringTask. AccessTheWebAsync next wants to calculate and return the length of the downloaded string, but the method can’t calculate that value until the method has the string.
Therefore, AccessTheWebAsync uses an await operator to suspend its progress and to yield control to the method that called AccessTheWebAsync. AccessTheWebAsync returns a Task(Of Integer) or Task<int> to the caller. The task represents a promise to produce an integer result that’s the length of the downloaded string.
Inside the caller (the event handler in this example), the process is repeated. The caller might do other work that doesn’t depend on the result from AccessTheWebAsync before awaiting that result, or the caller might await immediately. When the event handler reaches an await expression, the application focuses on the completion of GetStringAsync. The event handler is waiting for AccessTheWebAsync, and AccessTheWebAsync is waiting for GetStringAsync.
- GetStringAsync completes and produces a string result. The string result isn’t returned by the call to GetStringAsync in the way that you might expect. (Remember that the method already returned a task in step 3.) Instead, the string result is stored in the task that represents the completion of the method, getStringTask. The await operator retrieves the result from getStringTask. The assignment statement assigns the retrieved result to urlContents.
- When AccessTheWebAsync has the string result, the method can calculate the length of the string. Then the work of AccessTheWebAsync is also complete, and the waiting event handler can resume. In the full example at the end of the topic, you can confirm that the event handler retrieves and prints the value of the length result.
If you are new to asynchronous programming, take a minute to consider the difference between synchronous and asynchronous behavior. A synchronous method returns when its work is complete (step 5), but an async method returns a task value when its work is suspended (steps 3 and 6).
When the async method eventually completes its work, the task is marked as completed and the result, if any, is stored in the task.
Async away for speed and performance!
Contact us if you need advice on Asynchronous programming for your business.
Synetec is an Agile solutions provider with expertise in diverse development technologies, such as Angular, the .Net Framework, SQL Server and other cloud friendly data stores. We are certified and have successfully delivered projects across different cloud technology stacks such as Microsoft Azure and AWS, delivering integration and development solutions since 2000.
We work with a number of the UK’s most respected financial institutions to deliver a range of innovative solutions. We have expertise in working with both established businesses as well as start-ups and extreme growth businesses.