In the context of ASP.NET, why doesn't Task.Run(…).Result deadlock when calling an async method?

前端 未结 2 794
青春惊慌失措
青春惊慌失措 2021-02-06 13:37

I created a simple WebApi project with a single controller and a single method:

public static class DoIt
{
    public static async Task GetStrAsync         


        
2条回答
  •  野的像风
    2021-02-06 14:07

    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.

提交回复
热议问题