Simple way to join multiple async calls in C#

Mark the method as async to take the execution to a separate thread. The method returns a Task which represents the process that the method is executed on.

In C# programming, async await keywords are used for asynchronous operations.

What is async await behavior in C#?

Let’s say you are calling a method in your code block that returns some value. During execution, the control looks at the method call and goes to that particular method and executes it and returns to the original calling block with some return value. Assuming that the other method execution took some 10 seconds of time, the caller block waits for 10 seconds before the code after the method call is executed.

This is called a blocking operation or a synchronous call – calling method waits until the called method execution is complete.

If the method called has some remote operation or time taking operation (such as HTTP calls, Database Queries etc.) the control holds up until the execution is complete – this causes the application to freeze for sometime until the method call is complete.

What is an asynchronous operation?

The alternative approach is called asynchronous call – the calling method doesn’t wait for the called method execution to complete. In this case, the called method execution is put into a separate Thread and the calling method continues with its own, without waiting for the call to complete.

Once the other execution is complete, the called method returns result to the original block where it is called with a result. The calling method then takes the result and further continues with it.

When you wish to take the method execution to a separate thread – you will mark the method as async. The method returns a Task which represents the process that the method is executed on.

using System;
using System.Threading.Tasks;

class MyAsyncComponentDemo
{
    public async Task CallingMethod()
    {
        await SayHelloAsync();
    }

    public async Task SayHelloAsync()
    {
        Console.WriteLine("Hello, World!");
        // an asynchronous operation
        await Task.Delay(1000);
        Console.WriteLine("Async operation completed!");
    }
}

To wait for an asynchronous method without having to freeze the application, you will use await keyword with the method call. This ensures that the method is executed in an asynchronous manner, while the calling method waits for the result without freezing the application.

How to async/await multiple api calls in C#

When the code needs to create multiple asynchronous calls and wait for all of them to complete, you will use Task.WhenAll() method that takes a list of Tasks created by the called async methods.

You can then await on the Task.WhenAll() that will complete only when all the Tasks are complete. The other method is Task.WhenAny(), which will complete if any of the Tasks are complete.

using System;
using System.Threading.Tasks;

class MyAsyncComponentDemo
{
    static async Task CallingMethod()
    {
        var tasks = new List<Task<int>>();
        for (int i = 0; i < 10; i++)
        {
            tasks.Add(PrintMessageAsync(i));
        }

        // Use Task.WhenAll to await the completion of all the tasks
        await Task.WhenAll(tasks);
        Console.WriteLine("All tasks completed!");
    }

    static async Task<int> PrintMessageAsync(int currentCounter)
    {
        await Task.Delay(1000);
        Console.WriteLine(currentCounter);
        return currentCounter;
    }
}

Summary

  • async await keywords are used for asynchronous operations
  • awaiting a process puts in a separate task and returns the reference to that task.
  • Once complete the runtime makes sure that the process starts execution back from where the await process occurs. This is called as continuation.
  • we can use Task.WhenAll() method over a list of Tasks, which will ensure all the calls within the collection are completed before flagging as complete.

Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *