I've encountered many situations while making a library where I wanted to make an asynchronous method synchronous. I usually do something like this:
async Task<object> DoSomethingAsync() { ... } // Original method
object DoSomethingSync()
{
return DoSomethingAsync().Result;
}
This works fine in most cases, but Imagine the body of the async method looking something like this:
async Task<object> DoSomethingAsync()
{
object result = await CallAServiceAsync().ConfigureAwait(true); // This is important
// Do something with the result on the caller's context (e.g. UI updates)
return result;
}
The thread is going to run, return to the caller, do the equivalent of a .Wait()
on the Task (in .Result
). When CallAServiceAsync()
will return, it's going to try to get the original context back, but will deadlock because of the .Result
that's waiting.
I could use Task.Run(()=>DoSomethingAsync()).Result
, but I feel like there should be a simpler/better way of doing it. I don't believe I need to run the code on another thread each time.