I recently come to a deadlock issue similar at the one described here: An async/await example that causes a deadlock
This question is not a duplicate of the one below.
Because I have access to the async part of the code I have been able to use the solution described by @stephen-cleary in his blog post here: http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
So I added ConfigureAwait(false) on the first awaited Task.
I can't use the second solution (put async everywhere) because of the amount of impacted code.
But I keep asking myself, what if I can't modify the called async code (ex: extern API).
So I came to a solution to avoid the dead lock. A way to Join the task. By Join I mean a way to wait for the targeted task to end without blocking other tasks that's run on the current thread.
Here is the code:
public static class TaskExtensions
{
public static void Join(this Task task)
{
var currentDispatcher = Dispatcher.CurrentDispatcher;
while (!task.IsCompleted)
{
// Call back the dispatcher to allow other Tasks on current thread to run
currentDispatcher.Invoke(delegate { }, DispatcherPriority.SystemIdle);
}
}
}
I want to emphasize that I'm not sure that the correct name for this method is Join.
My question is why Task.Wait() is not implemented this way or may be optionally used this way ?