Jam*_*uth 6 c# events asynchronous httpmodule
你如何设置它们?
如果我在HttpModule中有以下代码.
public static event EventHandler<PostProcessingEventArgs> OnPostProcessing;
Run Code Online (Sandbox Code Playgroud)
并在使用的异步PostAuthorizeRequest任务中设置EventHandlerTaskAsyncHelper.
// Fire the post processing event.
EventHandler<PostProcessingEventArgs> handler = OnPostProcessing;
if (handler != null)
{
handler(this, new PostProcessingEventArgs { CachedPath = cachedPath });
}
Run Code Online (Sandbox Code Playgroud)
然后使用它来点击它.
ProcessingModule.OnPostProcessing += this.WritePath;
private async void WritePath(object sender, PostProcessingEventArgs e)
{
await Task.Factory.StartNew(() => Debug.WriteLine(e.CachedPath));
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误.
在异步操作仍处于挂起状态时完成异步模块或处理程序.
编辑
好吧,所以在我看到所有这些答案之前,我得到它不通过提升事件处理程序抛出错误,如下所示.
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);
}
Run Code Online (Sandbox Code Playgroud)
从我在下面看到的虽然这看起来不明智.
这个事件处理程序的唯一目的是允许某人在文件上运行更长时间的运行任务,例如使用jpegtran或pngout等内容来对图像进行后期处理以进一步优化它.最好的方法是什么?
AddOn*您可以使用类中的方法添加异步事件处理程序HttpApplication。我确信并非所有方法都支持 async void 方法。也许他们都没有。
尽管这些方法不直接支持任务,但要使用它们,您需要调整您的任务以与 ASP.NET 在此处使用的 APM 模式兼容。
也许它只是示例代码,但您Task.Factory.StartNew在 Web 应用程序的上下文中使用它没有帮助。