What's the “right way” to use HttpClient synchronously?

后端 未结 2 1029
终归单人心
终归单人心 2020-12-24 07:13

I used quote marks around \"right way\" because I\'m already well aware that the right way to use an asynchronous API is to simply let the asynchronous behavior propagate th

相关标签:
2条回答
  • 2020-12-24 07:35

    You could also look at using Nito.AsyncEx, which is a nuget package. I've heard of issues with using Task.Run() and this this addresses that. Here's a link to the api docs: http://dotnetapis.com/pkg/Nito.AsyncEx/4.0.1/net45/doc/Nito.AsyncEx.AsyncContext

    And here's an example for using an async method in a console app: https://blog.stephencleary.com/2012/02/async-console-programs.html

    0 讨论(0)
  • 2020-12-24 07:37

    Try following-

    var task = Task.Run(() => myHttpClient.GetAsync(someUrl)); 
    task.Wait();
    var response = task.Result;
    

    Use it only when you cannot use async method.

    This method is completely deadlock free as mentioned on msdn blog- https://blogs.msdn.microsoft.com/jpsanders/2017/08/28/asp-net-do-not-use-task-result-in-main-context/

    0 讨论(0)
提交回复
热议问题