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

Calling an asynchronous method from a synchronous method in C# can be achieved by using the Task.Run or TaskFactory.StartNew methods to offload the asynchronous work to a separate thread. Here's an example using the async and await keywords along with Task.Run:

csharp

using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.WriteLine("Synchronous method started.");
        
        // Call the asynchronous method using Task.Run
        await Task.Run(AsynchronousMethod);
        
        Console.WriteLine("Synchronous method completed.");
    }

    static async Task AsynchronousMethod()
    {
        Console.WriteLine("Asynchronous method started.");
        
        // Simulate asynchronous work
        await Task.Delay(2000);
        
        Console.WriteLine("Asynchronous method completed.");
    }
}

In this example:

    The Main method is synchronous and uses the async keyword, allowing you to use the await keyword within it.
    The AsynchronousMethod method is asynchronous and performs some asynchronous work using Task.Delay.
    To call the AsynchronousMethod from the Main method, you use Task.Run to start the asynchronous method on a separate thread. The await keyword then waits for the completion of the asynchronous method.

When you run the code, you'll see that the asynchronous method starts running independently of the synchronous method, and the program output reflects this asynchronous behavior.

Keep in mind that using Task.Run to offload asynchronous work from synchronous methods can be useful in certain scenarios, but it's important to understand the threading implications and whether it's appropriate for your specific use case. Additionally, mixing synchronous and asynchronous code should be done carefully to avoid deadlocks or other synchronization issues.

Comments