[C# Basics] Asynchronous programming in C#


Staff member
May 28, 2020
United States
When programming there are sometimes tasks that take a while to complete, for example I/O bound tasks (tasks that involve reading/writing data to disk storage). On slower mechanical hard drives (compared to solid state drives) the read and write operations per second are very limited, as a result when writing code that deals with files on a hard drive you may have to wait a few seconds before it completes to move onto the next task in your program. This post explains asynchronous programming and how it solves this problem.

For example, Imagine you write a program to open a website and save a screenshot of it. You’ll need to open a temporary file for writing, download the website, and write the screenshot data to the file and close it.

In a synchronously programmed application these steps would have to be performed in order one at a time.

In contrast, in an asynchronously programmed application, you could tell C# to open the file and while you’re waiting for the I/O bound task to complete you could go ahead and fetch the webpage and start generating the task, after the file has successfully open write the data to it, wait and return a successful response.

While this programming model requires compatible code (all code needs to be written asynchronously, otherwise the code will become synchronously bound and you’ll lose out on the performance benefits of asynchronous code). When using async programming, you can complete I/O bound tasks at a faster.

How to write asynchronous code in C#

Writing asynchronous code is relatively straightforward and involves the use of a few keywords. Your method signature must include the async keyword and your method name should end in the word Async as is the convention on C#. When calling an I/O bound method you should prefix it with the await keyword. Take a look at the following code example to see asynchronous code in action.

public async Task<bool> WriteWebPageScreenShotToFileAsync(string url, string filePath)
  var image = await GenerateScreenshotOfWebsiteByteArray(url); // awaits fetching the website, taking a screenshot, and creates a byte array of the screenshot
  await File.WriteAllBytesAsync(filePath, image); // awaits writing the byte array data to a file.
  return true; // returns true letting the calling method know that processing is complete.