Question

I have method that does asynchronous call to web service. Something like that:

public static async Task<ReturnResultClass> GetBasicResponseAsync()
{
    var r = await SomeClass.StartAsyncOp();
    return await OtherClass.ProcessAsync(r);
}

And I want to provide synchronous alternative:

public static ReturnResultClass GetBasicResponse()
{
    return GetBasicResponseAsync().Result;
}

But it blocks on Result call. Because it is called on the same thread as a async operations. How can I get result synchronously ?

Thanks!

Was it helpful?

Solution

You're right, if you're in a GUI application, the continuation part(s) of an async method will execute on the UI thread by default. And if you execute synchronous wait for the same Task on the UI thread at the same time, you will get a deadlock.

If it's your application, you can solve this by simply not waiting for the task synchronously.

If you're just writing a library, you can fix this by using ConfigureAwait(false). This way, the continuation part of the method will not execute on the captured context (the UI thread in GUI applications), but instead on a ThreadPool thread.

public static async Task<ReturnResultClass> GetBasicResponseAsync()
{
    var r = await SomeClass.StartAsyncOp().ConfigureAwait(false);
    return await OtherClass.ProcessAsync(r).ConfigureAwait(false);
}

Of course, the ideal solution is to not use synchronous operations in your GUI apps and use ConfigureAwait() in your library, so that others can use synchronous versions of the methods, if they want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top