如何设置它们?
如果我在 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/