Sobes.tech
Junior — Middle

How can you call an asynchronous function from a synchronous method?

sobes.tech AI

Answer from AI

In C#, calling an asynchronous function from a synchronous method can be done in several ways, but caution is needed to avoid deadlocks.

The simplest way is to use .GetAwaiter().GetResult() or .Result:

public async Task<int> AsyncMethod()
{
    await Task.Delay(1000);
    return 42;
}

public int SyncMethod()
{
    // Calling an async method from sync code
    int result = AsyncMethod().GetAwaiter().GetResult();
    return result;
}

However, using .Result or .Wait() can lead to deadlocks, especially in UI or ASP.NET contexts.

If possible, it's better to make the calling method asynchronous or use the "async all the way" pattern.

If that's not possible and you're confident in the context, GetAwaiter().GetResult() is a safer way, as it throws the original exception rather than an AggregateException.