Ian*_*ton 7 asynchronous exception-handling asp.net-mvc-3
我有这个......
public void FooAsync()
{
AsyncManager.OutstandingOperations.Increment();
Task.Factory.StartNew(() =>
{
try
{
doSomething.Start();
}
catch (Exception e)
{
AsyncManager.Parameters["exc"] = e;
}
finally
{
AsyncManager.OutstandingOperations.Decrement();
}
});
}
public ActionResult FooCompleted(Exception exc)
{
if (exc != null)
{
throw exc;
}
return View();
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法将异常传递回ASP.net?
干杯,伊恩.
Task会抓住你的例外.如果你调用task.Wait()它,它会将任何捕获的异常包装AggregateException在一起并抛出它.
[HandleError]
public void FooAsync()
{
AsyncManager.OutstandingOperations.Increment();
AsyncManager.Parameters["task"] = Task.Factory.StartNew(() =>
{
try
{
DoSomething();
}
// no "catch" block. "Task" takes care of this for us.
finally
{
AsyncManager.OutstandingOperations.Decrement();
}
});
}
public ActionResult FooCompleted(Task task)
{
// Exception will be re-thrown here...
task.Wait();
return View();
}
Run Code Online (Sandbox Code Playgroud)
简单地添加[HandleError]属性是不够的.由于异常发生在另一个线程中,我们必须将异常返回到ASP.NET线程,以便对它执行任何操作.只有在我们从正确的位置抛出异常之后,该[HandleError]属性才能完成其工作.
| 归档时间: |
|
| 查看次数: |
1936 次 |
| 最近记录: |