An async/await example that causes a deadlock

后端 未结 5 1987
暗喜
暗喜 2020-11-21 13:32

I came across some best practices for asynchronous programming using c#\'s async/await keywords (I\'m new to c# 5.0).

One of the advices gi

5条回答
  •  孤城傲影
    2020-11-21 14:21

    A work around I came to is to use a Join extension method on the task before asking for the result.

    The code look's like this:

    public ActionResult ActionAsync()
    {
      var task = GetDataAsync();
      task.Join();
      var data = task.Result;
    
      return View(data);
    }
    

    Where the join method is:

    public static class TaskExtensions
    {
        public static void Join(this Task task)
        {
            var currentDispatcher = Dispatcher.CurrentDispatcher;
            while (!task.IsCompleted)
            {
                // Make the dispatcher allow this thread to work on other things
                currentDispatcher.Invoke(delegate { }, DispatcherPriority.SystemIdle);
            }
        }
    }
    

    I'm not enough into the domain to see the drawbacks of this solution (if any)

提交回复
热议问题