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

后端 未结 2 1046
终归单人心
终归单人心 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: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/

提交回复
热议问题