c# - HttpModule 中的异步事件处理程序

标签 c# events asynchronous httpmodule

如何设置它们?

如果我在 HttpModule 中有以下代码。

public static event EventHandler<PostProcessingEventArgs> OnPostProcessing;

并在使用 EventHandlerTaskAsyncHelper 设置的异步 PostAuthorizeRequest 任务中。

// Fire the post processing event.
EventHandler<PostProcessingEventArgs> handler = OnPostProcessing;
if (handler != null)
{
    handler(this, new PostProcessingEventArgs { CachedPath = cachedPath });
}

然后使用它进入它。

ProcessingModule.OnPostProcessing += this.WritePath;    

private async void WritePath(object sender, PostProcessingEventArgs e)
{
    await Task.Factory.StartNew(() => Debug.WriteLine(e.CachedPath));
}

我收到以下错误。

An asynchronous module or handler completed while an asynchronous operation was still pending.

编辑

好吧,在我看到所有这些答案之前,我通过如下引发事件处理程序来避免抛出错误。

EventHandlerTaskAsyncHelper postProcessHelper = 
new EventHandlerTaskAsyncHelper(this.PostProcessImage);

context.AddOnPostRequestHandlerExecuteAsync(postProcessHelper.BeginEventHandler,
postProcessHelper.EndEventHandler);

private Task PostProcessImage(object sender, EventArgs e)
{
    HttpContext context = ((HttpApplication)sender).Context;
    object cachedPathObject = context.Items[CachedPathKey];

    if (cachedPathObject != null)
    {
        string cachedPath = cachedPathObject.ToString();

        // Fire the post processing event.
        EventHandler<PostProcessingEventArgs> handler = OnPostProcessing;
        if (handler != null)
        {
            context.Items[CachedPathKey] = null;
            return Task.Run(() => handler(this, 
            new PostProcessingEventArgs { CachedImagePath = cachedPath }));
        }
    }

    return Task.FromResult<object>(null);
}

从我在下面看到的情况来看,这似乎是不明智的。

此事件处理程序的唯一目的是允许某人在文件上运行运行时间更长的任务,例如使用 jpegtran 或 pngout 之类的东西对图像进行后期处理以进一步优化它。最好的方法是什么?

最佳答案

您可以使用 HttpApplication 中的 AddOn* 方法添加异步事件处理程序类(class)。我确定并非所有方法都支持 async void 方法。也许他们都不是。

要使用这些方法,尽管它们不直接支持任务,you need to adapt your task to be compatible with the APM pattern which ASP.NET uses here .

也许它只是示例代码,但您使用 Task.Factory.StartNew 在 Web 应用程序的上下文中没有帮助。

关于c# - HttpModule 中的异步事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25348361/

相关文章:

c# - 在 Visual Studio 中复制断点的简单方法

c# - 遍历特定的Azure Blob存储目录并删除所有文件

.net - 异步上传 Azure Blob : BeginUploadFromStream vs. BackgroundWorker

javascript - bcrypt.compare() 是异步的,这是否一定意味着一定会发生延迟?

javascript - 从mssql模块中的异步函数返回数据

c# - 您可以将 SignalR 与 Visual Studio 2012 一起使用吗?

c# - 从数据表中删除具有行值的列

excel - 使用 workbook_sheetchange 事件在行范围内使数值为负

c# - 将应用程序中的所有事件归为一类是否是一种不好的做法?

jquery - 根据条件排除点击事件?