【发布时间】:2014-08-17 10:29:23
【问题描述】:
您如何设置它们?
如果我在 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));
}
我收到以下错误。
异步模块或处理程序在异步完成时完成 操作仍在等待中。
编辑
好的,所以在我看到所有这些答案之前,我得到它不会通过引发事件处理程序引发错误,如下所示。
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 之类的东西对图像进行后处理以进一步优化它。最好的方法是什么?
【问题讨论】:
-
This 可能会有所帮助
-
如果调用线程只是要等待它完成,我不明白启动一个新线程的意义?
-
该代码仅用于测试/演示以查看它是否正在触发。实际消耗方法会很耗时
标签: c# events asynchronous httpmodule