deadlock even after using ConfigureAwait(false) in Asp.Net flow

后端 未结 3 1324
无人及你
无人及你 2020-12-20 12:29

I\'m hitting deadlock even after using ConfigureAwait(false), below is the sample code.

As per the sample http://blog.stephencleary.com/2012/02/async-a

3条回答
  •  一向
    一向 (楼主)
    2020-12-20 13:12

    I had the same problem. "ConfigureAwait(false)" can not always avoid dead lock.

    public class HomeController : Controller
    {
        public async Task Index()
        {
            // This works !
            ViewBag.Title = GetAsync().Result;
    
            // This cause deadlock even with "ConfigureAwait(false)" !
            ViewBag.Title = PingAsync().Result;
    
            return View();
        }
    
        public async Task GetAsync()
        {
            var uri = new Uri("http://www.google.com");
            return await new HttpClient().GetStringAsync(uri).ConfigureAwait(false);
        }
    
        public async Task PingAsync()
        {
            var pingResult = await new Ping().SendPingAsync("www.google.com", 3).ConfigureAwait(false);
    
            return pingResult.RoundtripTime.ToString();
        }
    }
    

    For the above code, "GetAsync()" works while "PingAsync()" doesn't.

    But I found that if I wrap the async call into a new task, and wait this task, PingAsync() will work event without "ConfigureAwait(false)":

    var task = Task.Run(() => PingAsync());
    task.Wait();
    ViewBag.Title = task.Result;
    

    I don't know the reason, maybe someone can tell me the difference.

提交回复
热议问题