I created a simple WebApi project with a single controller and a single method:
public static class DoIt
{
public static async Task GetStrAsync
I'll give you as short answer the other way around: how to produce a deadlock:
Lets start in a Click
handler that is executing synchronous and offloading some async call to a separate Task, then waiting for the result
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
var t = Task.Run(() => DeadlockProducer(sender as MenuItem));
var result = t.Result;
}
private async Task DeadlockProducer(MenuItem sender)
{
await Task.Delay(1);
Dispatcher.Invoke(() => sender.Header = "Life sucks");
return 0;
}
The async method is doing another bad thing: it tries to bring some UI change synchronously, but the UI thread is still waiting for the task result...
So basically, Task.Run
is half way out and will work for a lot of well formed async code, but there are ways to break it, so its not a reliable solution.
This sample code was written in context of WPF, but I guess ASP.Net could be abused to produce similar behavior.