在Global.asax启用Session_Start时,MVC异步操作表现为同步

时间:2016-08-31 11:37:00

标签: asp.net-mvc

(使用MVC 5.2.3和Visual Studio 2015中的Net Framework 4.5.2创建的空白应用程序)。示例显示带有异步方法的控制器,以显示指示器(GetProgressAsync)中的进度,假设服务器正忙一段时间(CommitAsync):

public class HomeController : Controller
{
public static int Progress = 0;

public async Task<ActionResult> GetProgressAsync()
{
    Task<ActionResult> task = Task.Run<ActionResult>(() =>
    {
        var result = new ContentResult();
        result.Content = string.Format("Progreso: {0}", Progress);
        return result;
    });

    return await task;
}

public async Task<ActionResult> CommitAsync()
{
    Task<ActionResult> task = Task.Run<ActionResult>(() =>
    {
        Progress = 0;

        while (Progress < 100)
        {
            Progress++;
            System.Threading.Thread.Sleep(100);
        }

        var result = new ContentResult();
        result.Content = string.Format("{0} : Commit completado", DateTime.Now.ToShortTimeString());
        return result;
    });

    return await task;
}
}

如果在Global.asax.cs中未启用Session_Start / Session_End方法,则控制器将表现为异步,并且可以监视任务的进度(即从浏览器)。

public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

//WARNING: habilitar estos métodos hace que no funcionen las llamadas Async/Await
//WARNING: enabling this methods hang Async/Await support
//protected void Session_Start(object sender, EventArgs e)
//{
//    // TODO
//}

//protected void Session_End(object sender, EventArgs e)
//{
//    // TODO
//}
}

启用会话方法Session_Start / Session_End时会识别错误。控制器仅作为第一个请求的异步工作。后续的CommitAsync请求将挂起应用程序,并且在CommitAsync完成之前,不会处理对GetProgressAsync的请求。

1 个答案:

答案 0 :(得分:0)

它在控制器上使用此属性:

[SessionState(SessionStateBehavior.ReadOnly)]