Skip to content

Introduction to Asynchronous Programming with C#

Introduction to Asynchronous Programming with C#
Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!

Introduction to Asynchronous Programming with C#

Asynchronous programming aims to maximize the use of resources, such as CPU time and memory, and to minimize the time it takes for a program to complete a task.

In today’s fast-paced digital world, users expect applications to be quick and responsive, even when dealing large amounts of data. To meet these demands, developers must turn to asynchronous programming. By breaking down long-running tasks into smaller, asynchronous tasks, we can ensure that our applications remain quick and responsive, even when processing large amounts of data.

Asynchronous programming allows the program to continue executing other tasks. At the same time, it waits for a task to complete, reducing the time it takes for a program to complete a task.

This article will explore how to implement asynchronous programming in C# using the Task class and the async keyword. We’ll also look at how to use the await keyword to wait for asynchronous tasks to complete and how to use the Task.WhenAll method to wait for multiple tasks to complete.

By the way, if you are interested in learning more about APIs, we also have several articles on this topic! Make sure to check them out! Like this one, about the GET method and How to Call GET API in C#!

So whether you’re a beginner or an experienced developer, this article will give you a solid understanding of asynchronous programming in C# and help you create fast and responsive applications.

 

Create a new C# Console App

To begin, we’ll need to create a new C# console application in Visual Studio.

  • Open Visual Studio and click on “Create a new project.”

Introduction to Asynchronous Programming with C#

Introduction to Asynchronous Programming with C#

  • Select “Console App (.NET 6)” from the list of templates.

Introduction to Asynchronous Programming with C#

Introduction to Asynchronous Programming with C#

  • Give your project a name, for example “AsyncInCsharp” and click on “Create.”
Introduction to Asynchronous Programming with C#

Introduction to Asynchronous Programming with C#

 

Getting Started with the Main Method

Let’s start with the Main method. The Main method is the entry point of our program and where all the magic happens. The first thing we need to do is add the async keyword to the Main method signature. This keyword tells C# that the Main method is asynchronous, meaning it can run multiple tasks simultaneously.

Getting Data Asynchronously

The next step is to retrieve data from two different sources. In this case, we’re retrieving weather data and news articles. We do this by calling two separate methods, GetWeatherAsync and GetNewsAsync. These methods are asynchronous and retrieve data from the API. We use the HttpClient class to retrieve the data, which is part of the System.Net.Http namespace. HttpClient is a modern HTTP client that supports many advanced features, including asynchronous programming.

By the way, to make this work, you must have an API key from both openweathermap.org/ as well as newsapi.org/. By signing up you should be able to get an API key for both so don´t worry!

Calling both tasks in the Main Method

Now that both methods are implemented, we will have to call them both in the Main method. This can be done as usual as if it was a normal method. Like this:

Waiting for Both Tasks to Complete

Once both methods have been called, we use the Task.WhenAll method to wait for both tasks to be complete. This method takes an array of tasks and blocks the calling thread until all tasks are completed.

Displaying the results

Once both the weather and news tasks are completed, we can then display the results. This is done using the Console.WriteLine method. The results of the tasks are stored in the Result property of the tasks, which is accessed like this:

In this code, we first print the word “Weather:” to the console and then the result of the weather task. Next, we print a blank line using Console.WriteLine() to create some space and then print the word “News:” followed by the result of the news task. Finally, we add a prompt for the user to exit the program:


Now you should be getting the result of both API calls asynchronously as your output. This would look like this:


 

The project can sometimes hang with a “Bad Request” Error. This is generally not a genuine concern but occurs due to rate limiting within the News API. We can see this error if we implement a basic error handling system like this within the GetNewsAsync() method:

 

If we have this error, the result of running the program again would be the following:

 

Generally, if that is your case, if you simply type into your search bar the URL from your GetStringAsync() method. So something like this: https://newsapi.org/v2/top-headlines?country=us&apiKey=YOURAPIKEY.  (Make sure to change “YOURAPIKEY” for your actual API key) And then rerun the program; it will succeed in most cases.

Naturally, if that is still not the case, let us know in the comments below!

Great! However, this might look an awful lot like multithreading to you. And for sure, that is understandable, but let me explain why it is not the same.

Differences and similarities between multithreading and asynchronous programming.

Multithreading and asynchronous programming are often used interchangeably, but they are not exactly the same thing. Multithreading involves running multiple threads in parallel, while asynchronous programming involves executing tasks in a non-blocking way, allowing the program to continue executing other tasks while the asynchronous task is running in the background.

One similarity between multithreading and asynchronous programming is that they both allow you to run multiple tasks simultaneously, improving the performance and responsiveness of your applications.

In C#, asynchronous programming can be implemented using the async and await keywords. This makes it easier to write asynchronous code and provides a cleaner syntax compared to traditional multithreading.

If you want to learn more about multithreading in C#, check out our article on Multithreading in C#!

And that’s it! With these concepts in mind, you should now understand the difference and similarities between multithreading and asynchronous programming in C#.

 

Conclusion: Introduction to Asynchronous Programming with C#

Async programming is a powerful tool that allows developers to write efficient, responsive applications. By breaking down long-running tasks into smaller, asynchronous tasks, we can create quick and responsive applications, even when dealing with large amounts of data. In this article, we have seen how to use the async and await keywords to create asynchronous tasks and how to wait for them to complete. With this knowledge, you can now create your own asynchronous applications and improve the user experience of your applications.

And don’t forget that when in doubt, you can always refer to this article to help you understand to use asynchronous Programming with C#. By the way, if this sounds an awful lot like multithreading to you and you wonder what the differences may be, make sure to check out this next article about Multithreading in C#! Coming soon!
If you want to skyrocket your C# career, check out our powerful ASP.NET FULL-STACK WEB DEVELOPMENT COURSE, which also covers test-driven development and C# software architecture.
Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!
Enter your email and we will send you the PDF guide:
Enter your email and we will send you the PDF guide