How to call an async method in a sync method in C#

By | 2. March 2023

To call an async method in a sync method in C#, you have a few options:

– You can use the GetAwaiter().GetResult() method to block the calling thread until the async method completes and returns the result¹⁴.
– You can use the Wait() or Result property of the Task object returned by the async method to block the calling thread until the async method completes and returns the result⁴. However, this approach can cause deadlocks if the async method depends on the calling thread to complete, and should be avoided in such cases⁴.
– You can use Task.Run() to start the async method on a separate thread pool thread and wait for it to complete⁵. However, this solution requires that the async method will work in a different context than the calling thread, so it can’t update UI elements or access some other resources that are tied to a specific thread⁵.

Here is an example of using GetAwaiter().GetResult() to call an async method synchronously:

using System;
using System.Threading.Tasks;

public class Program
{
public static void Main()
{
Console.WriteLine("Calling sync method...");
SyncMethod();
Console.WriteLine("Done.");
}

public static void SyncMethod()
{
Console.WriteLine("Calling async method...");
var result = AsyncMethod().GetAwaiter().GetResult();
Console.WriteLine("Async result: " + result);
}

public static async Task AsyncMethod()
{
await Task.Delay(1000); // simulate some asynchronous work
return 42; // return some value
}
}

Here is an example of using Wait() or Result to call an async method synchronously:

using System;
using System.Threading.Tasks;

public class Program
{
public static void Main()
{
Console.WriteLine("Calling sync method...");
SyncMethod();
Console.WriteLine("Done.");
}

public static void SyncMethod()
{
Console.WriteLine("Calling async method...");
var result = AsyncMethod().GetAwaiter().GetResult();
Console.WriteLine("Async result: " + result);
}

public static async Task AsyncMethod()
{
await Task.Delay(1000); // simulate some asynchronous work
return 42; // return some value
}
}

 


(1) Calling async method synchronously in C# – iditect.com.
(2) How to call asynchronous method from synchronous method in C#?.
(3) How to call asynchronous method from synchronous method in C#?.
(5) C# Asynchronous | Working of Asynchronous Method in C# | Examples – EDUCBA.
(6) c# – Calling Async Method from Sync Method – Stack Overflow.

Leave a Reply