Get the result of an asynchronous method

I have a method that makes an asynchronous call to a 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 a synchronous alternative:

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

But it is blocked when called Result. Because it is called on the same thread as async operations. How to get the result synchronously?

Thank!

+5
source share
1 answer

You are right, if you are in a GUI application, part of the continuation of the method asyncwill be executed by default user interface thread. And if you simultaneously synchronously wait for the same task in the user interface thread, you will get a dead end.

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

, , ConfigureAwait(false). , ( GUI), ThreadPool.

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

, ConfigureAwait() , , .

+8

All Articles