The Best Guide to Understand C# Async Await.

The async keyword converts a method into an async method, allowing you to use the await keyword in the method's body. When the await keyword is used, the calling method is suspended and control is returned to the caller until the awaited task is completed. The await keyword can only be used within an async method. This async await tutorial in C# will teach us everything we need to know about async and await in C#, complete with code examples.

Now, go ahead and begin learning C# async await through the following docket below.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Introduction to Asynchronous Programming

Asynchronous programming, whether in .Net or another language, is something you've probably heard of. This tutorial will explain how to understand the concept easily, why and when you need to write asynchronously, the structure of async/await, and some examples to help you understand the concept.

Asynchronous programming allows you to divide your logic into available tasks, which allow you to perform long-running operations such as reading a large file, making an API call, downloading a resource from the web, or performing a complex calculation without blocking the execution of your application on the UI or service.

The .NET framework's async and await modifiers make it simple and easy to convert your code from synchronous programming to asynchronous programming.

As a result, you can call an async method independently by passing it a task object, then do some unrelated work, and then await that task to see if it has already finished. In which case it will return the value from the task and then use it in subsequent statements, or if it has not yet finished, in which case the execution will return to the caller of the async procedure. The program will normally execute without blocking the UI or the running service, once the task is done.

Asynchronous programming patterns include:

  •  Asynchronous Programming Model (APM)
  •  Event-based Asynchronous Pattern (EAP)
  • Task-based Asynchronous Pattern (TAP) 

It is recommended to use the Task-based Asynchronous Pattern whenever you want to have an asynchronous implementation in your application. On top of that, you can use the async/await feature to enhance the structure of your application further, making your code more organized and well-maintained.

You can incorporate the benefits of asynchronous programming into your project with a few minor changes to your code.

After learning what asynchronous programming is in this C# Async Await tutorial, you will look at the benefits of asynchronous programming.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Benefits of Asynchronous Programming

The following are the primary advantages of asynchronous programming with async/await:

  • Improve your application's performance and responsiveness, especially if you have long-running operations that don't require blocking the execution. In this case, you can do other things while you wait for the long-running Task to finish.
  • Organize your code in a much more neat and readable manner than the boilerplate code of traditional thread creation and handling. You write less code with async/await, which is more maintainable than with previous asynchronous programming methods such as basic tasks.
  • BackgroundWorker, used in Windows forms desktop applications, has been replaced by async/await.
  • You use the most recent language feature upgrades, such as async/await, introduced in C# 5. Some improvements have been added to the feature, such as for each async and generalized async type like ValueTask.

In this C# async await tutorial, you will learn why we should write asynchronous code.

Why Write Asynchronous Programming?

Asynchronous code is typically written for two distinct purposes:

  1. I/O bound Code: When you want to perform an input/output operation, such as downloading a large file from the network, reading a large file, or accessing a database resource. In this case, the await keyword is applied to an async method that returns a Task or Task.
  2. CPU bound Code:  This is used when a complex in-app calculation is required, such as calculating and displaying the remaining distance to the finish line in a racing game. Imagine if it was done synchronously and the UI was blocked while calculating the remaining distance while the car was moving?! As a result, in the CPU-bound case, you use the await keyword on an async method that will run on a background thread via the method Task. Run().

The responsiveness or running state of your application's UI or service should not be blocked or affected in either scenario.

For each async method, .Net framework will create a state for each of the async methods. Net framework will produce a state machine to keep track of the calls and what should be done once the current Task has been completed. Check out this in-depth article on async/await compilation and state machines. Also, read Async in Depth to learn more about Async and what happens behind the scenes of Task and TaskT>.

Moving forwards on this C# async await tutorial, you will look at the structure of async-await in C#.

Structure of Async/Await Keyword

The following changes should be made to a normal method to make it asynchronous and use the async/await keywords:

The keyword async should be included in the method definition; this keyword does nothing except allow you to use the keyword await in the procedure.

  • The method return type should be changed to return void, Task, or TaskT>, where T is the return data type, as in this example.

GetUserNameAsync() is a public async TaskString> function.

  • An asynchronous method name should end with the word 'Async,' so if you have a method called GetUserName, it should be changed to GetUserNameAsync.

When you add the keyword async to the method definition, you will use the await keyword within this method, allowing you to await the method as needed. If you don't include the await keyword, the method will be treated as normal or synchronous.

It is important to note that, while returning void in an async method is permitted, it should not be used in most cases because the other two return types, Task and TaskT>, represent void and T after the available method completes and returns the result. As a result, void as a return type should only be restricted to event handlers.

In the following section of this C# async await tutorial, you will look at input-output bound code async and await in C#.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

I/O Bound Code Async/Await

using System;

using System.Net.Http;

using System.Threading.Tasks;

namespace AsyncApp

{

    class Program1

    {

        private const string URL1 = "https://docs.microsoft.com/en-us/dotnet/csharp/csharp";

        static void Main(string[] args)

        {

            DoSynchronousWork();

            var someTask = DoSomethingAsync();

            DoSynchronousWorkAfterAwait();

            someTask.Wait(); //this is a blocking call, use it only on Main method

            Console.ReadLine();

        }

        public static void DoSynchronousWork()

        {

            // You can do whatever work is needed here

            Console.WriteLine("1. Doing work synchronously");

        }

        DoSomethingAsync() static async Task / A Task return type will eventually result in avoidance.

        {

            Console.WriteLine("2. Async task has begun");

            await GetStringAsync(); // We are looking forward to the Async Method. GetStringAsync

        }

        static async Task GetStringAsync()

        {

            using (var httpClient = new HttpClient())

            {

                Console.WriteLine("3. Waiting the result of GetStringAsync of Http Client");

                string result1 = await httpClient.GetStringAsync(URL1); //The execution is halted here while GetStringAsync completes.

                //Once the above available is completed, the execution will resume from this line and below.

                //It will perform the magic of unwrapping the Taskstring> into the string using the await keyword (result one variable)

                Console.WriteLine("4. The awaited task has completed. Let's get the content length...");

                Console.WriteLine("5. The length of http Get for {URL1}");

                Console.WriteLine("6. {result1.Length} character");

            }

        }

        static void DoSynchronousWorkAfterAwait()

        {

            //This is the work we can do while waiting for the awaited Async Task to complete

            Console.WriteLine("7. While waiting for the async task to finish, we can do some unrelated work...");

            for (var i = 0; i <= 6; i++)

            {

                for (var j = i; j <= 6; j++)

                {

                    Console.Write("#");

                }

                Console.WriteLine();

            }


        }

    }

}

Output:

input-output-bound-code-async-await.

Following that, you will see CPU-bound async await code in C#.

CPU Bound Code Async/Await

using System;

using System.Threading.Tasks;

namespace AsyncApp

{

    class Program1

    {

        static void Main(string[] args)

        {

            var totalAfterTax1 = CalculateTotalAfterTaxAsync(50);

            DoSomethingSynchronous();

            totalAfterTax1.Wait();

            Console.ReadLine();

        }

        private static void DoSomethingSynchronous()

        {

            Console.WriteLine("Doing synchronous work");

        }

        static async Task<float> CalculateTotalAfterTaxAsync(float value1)

        {

            Console.WriteLine("Started CPU Bound code asynchronous task on a background thread");

            var result1 = await Task.Run(() => value1 * 1.2f);

            Console.WriteLine($"Finished Task. Total of {value1} after tax of 20% is {result1} ");

            return result1;

        }

    }

}

Output:

cpu-bound-code-async-await.

Finally, in this C# Async await tutorial, you will get a look at the summary of everything you have learned so far.

Accelerate your career as a skilled MERN Stack Developer by enrolling in a unique Full Stack Developer - MERN Stack Master's program. Get complete development and testing knowledge on the latest technologies by opting for the MERN Stack Developer Course. Contact us TODAY!

Next Steps

In this C# async and await tutorial, you learned about asynchronous programming and its benefits. You also learned why you need to write asynchronous programming. Later, you looked at the structure of the async and await keywords, and finally, you looked at I/O and CPU bound code async and await with code examples.

If you want a complete study that goes beyond Mobile and Software Development, Simplilearn's Full Stack Developer - MERN Stack program will be ideal for you. This online coding Bootcamp, delivered in collaboration with Caltech CTME, covers the most in-demand programming languages and skills required for success in software development today. It's time to go out and explore.

Do you have any queries about this tutorial on the C# Async Await? Please place them in the comments section at the bottom of this page. Our experts will be glad to reply to your questions as earliest as possible!

About the Author

Kartik MenonKartik Menon

Kartik is an experienced content strategist and an accomplished technology marketing specialist passionate about designing engaging user experiences with integrated marketing and communication solutions.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.