How to call asynchronous method from synchronous method in C#?

15 September 2022 | Viewed 20605 times

What is an async method in C#?

An async method runs synchronously until it reaches its first await statement, and the method will be suspended until the awaited task is completed. In the meantime, control returns to the caller of the method.

What is synchronous and asynchronous methods in C#?

Synchronization means two or more operations happen sequentially.
Asynchronous means two or more operations are running in different contexts (thread) so that they can run concurrently and do not block each other.
A method in C# is made an asynchronous method using the async keyword in the method signature. You can have one or more await keywords inside an async method.

The following example defines an async method named "GetSquare"
Code
public async Task<int> GetSquare(int number)
{
await Task.Delay(1000);
return number*number;
}

How to call async method in non async method?

To call async method from a non async method we can use Task.Run method.
Task.Run is to execute CPU-bound code in an asynchronous way. Task.Run does this by executing the method on a thread pool and returning a Task representing the completion of that method.

Code
public void MyMethod ()
{
//without using await
Task.Run(()=> GetSquare(5));

// with await
var SqNum =Task.Run<int>(async()=>await GetSquare(5));
}


PreviousNext