首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >异步HttpModule MVC

异步HttpModule MVC
EN

Stack Overflow用户
提问于 2013-07-25 16:19:05
回答 1查看 2.9K关注 0票数 8

我有一个包含以下代码的同步HttpModule。

代码语言:javascript
复制
    /// <summary>
    /// Occurs as the first event in the HTTP pipeline chain of execution 
    /// when ASP.NET responds to a request.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">An <see cref="T:System.EventArgs">EventArgs</see> that 
    /// contains the event data.</param>
    private async void ContextBeginRequest(object sender, EventArgs e)
    {
        HttpContext context = ((HttpApplication)sender).Context;
        await this.ProcessImageAsync(context);
    }

当我试图从一个空的MVC4应用程序(NET4.5)运行模块时,我会得到以下错误。

此时无法启动异步操作。异步操作只能在异步处理程序或模块中启动,或者在页生命周期中的某些事件期间启动。如果在执行页时发生此异常,请确保该页标记为<%@ Page Async="true“%>。

我似乎遗漏了一些东西,但根据我的解读,错误不应该实际发生。

我已经挖了一遍,但我似乎找不到任何帮助,有人有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-25 17:49:39

因此,同步HttpModule事件处理程序中有异步代码,ASP.NET抛出一个异常,指示异步操作只能在异步处理程序/模块中启动。我觉得很直截了当。

要解决这个问题,您不应该直接订阅BeginRequest;相反,创建一个Task-returning“处理程序”,将其包装在EventHandlerTaskAsyncHelper中,并将其传递给AddOnBeginRequestAsync

就像这样:

代码语言:javascript
复制
private async Task ContextBeginRequest(object sender, EventArgs e)
{
  HttpContext context = ((HttpApplication)sender).Context;
  await ProcessImageAsync(context);

  // Side note; if all you're doing is awaiting a single task at the end of an async method,
  //  then you can just remove the "async" and replace "await" with "return".
}

并签署:

代码语言:javascript
复制
var wrapper = new EventHandlerTaskAsyncHelper(ContextBeginRequest);
application.AddOnBeginRequestAsync(wrapper.BeginEventHandler, wrapper.EndEventHandler);
票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17863503

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档