ASP.NET MVC WebApi控制器方法使用async假死超时问题
在一个ASP.NET MVC WebApi控制器方法中使用async标记为异步方法后,有时会假死超时。根本原因是同步方法和异步方法混合造成的死锁问题。
using System; namespace Demo { public class DemoController : ApiController { public async Task<string> DemoAction() { await Task.Delay(1000); return "OK"; } } }
因为async、await具有传染性,使用了它们则在方法上层都要依次传递。所以还需要在Filter、DelegatingHandler等中也使用async、await。
using System; namespace Demo.Filters { public class BaseFilterAttribute : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext filterContext) { } public override async void OnActionExecuting(ActionExecutingContext filterContext) { await …… } public override void OnResultExecuted(ResultExecutedContext filterContext) { } public override void OnResultExecuting(ResultExecutingContext filterContext) { } } }
using System; namespace Demo.Filters { public class CommonDelegatingHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { HttpResponseMessage response = await base.SendAsync(request, cancellationToken); return response; } } }