In the context of ASP.NET why not Task.Run (...). End the deadlock when calling the async method?

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

public static class DoIt
{
    public static async Task<string> GetStrAsync(Uri uri)
    {
        using (var client = new HttpClient())
        {
            var str = await client.GetStringAsync(uri);
            return str;
        }
    }
}

public class TaskRunResultController : ApiController
{
    public string Get()
    {
        var task = Task.Run(() =>
            DoIt.GetStrAsync(new Uri("http://google.com"))
        );
        var result = task.Result;

        return result;
    }
}

I have a good understanding of async / wait and tasks; almost religiously following Stephen Cleary. Existence just .Resultmakes me worry, and I expect it to slow down. I understand what Task.Run(...)is wasteful, causing the thread to be busy waiting for async to complete DoIt().

The problem is that this is not a deadlock, and it gives me a heartbeat.

, qaru.site/questions/500143/..., , SynchronizationContext.Current null, . , , , , , , ConfigureAwait(false) ( ) .Result.

?

+4
2

Result . - . A Result - , , .

Result , , , . - .

ASP.NET Core , Result . ( - , ).

, , .

, Task.Run . Task.Run(...).Result . Result , ( - ), , Task.Run .

Task.Run - ASP.NET( ), , . , Task.Run .

, , , ,

, . , .

, ConfigureAwait (false) ( ) .Result.

Result/context - , , . .

, , async ( ). .

+5

: :

Click, ,

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    var t = Task.Run(() => DeadlockProducer(sender as MenuItem));
    var result = t.Result;
}

private async Task<int> DeadlockProducer(MenuItem sender)
{
    await Task.Delay(1);
    Dispatcher.Invoke(() => sender.Header = "Life sucks");
    return 0;
}

: , ...

, Task.Run , , .

WPF, , ASP.Net , .

0

Source: https://habr.com/ru/post/1680367/


All Articles