Monday 6 August 2018

c# - Deadlock using Result and ConfigureAwait(true)

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 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 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.

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...