Different behavior when using ContinueWith or Async-Await

前端 未结 4 897
轻奢々
轻奢々 2020-12-28 10:28

When I use an async-await method (as the example below) in a HttpClient call, this code causes a deadlock. Replacing the async-await method with a t.C

4条回答
  •  囚心锁ツ
    2020-12-28 11:03

    I found the other solutions posted here did not work for me on ASP .NET MVC 5, which still uses synchronous Action Filters. The posted solutions don't guarantee a new thread will be used, they just specify that the same thread does not HAVE to be used.

    My solution is to use Task.Factory.StartNew() and specifying TaskCreationOptions.LongRunning in the method call. This ensures a new/different thread is always used, so you can be assured you will never get a deadlock.

    So, using the OP example, the following is the solution that works for me:

    public class MyFilter: ActionFilterAttribute {
    public override void OnActionExecuting(ActionExecutingContext filterContext) {
         // var user = _authService.GetUserAsync(username).Result;
    
         // Guarantees a new/different thread will be used to make the enclosed action
         // avoiding deadlocking the calling thread
         var user = Task.Factory.StartNew(
              () => _authService.GetUserAsync(username).Result,
              TaskCreationOptions.LongRunning).Result;
    }
    

    }

提交回复
热议问题