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!
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.
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With