Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get result of async method

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!

like image 997
gor Avatar asked Mar 03 '12 11:03

gor


People also ask

Can you return from an async function?

Async functions will always return a value. Using async simply implies that a promise will be returned, and if a promise is not returned, JavaScript automatically wraps it in a resolved promise with its value.

Can async method have return value?

Async methods can have the following return types: Task, for an async method that performs an operation but returns no value. Task<TResult>, for an async method that returns a value. void , for an event handler.

What does async function return JS?

Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.

What is the base return type for async methods?

Async methods have three possible return types: Task<TResult>, Task, and void. In Visual Basic, the void return type is written as a Sub procedure. For more information about async methods, see Asynchronous Programming with Async and Await (Visual Basic).


1 Answers

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.

like image 154
svick Avatar answered Oct 10 '22 09:10

svick