我有这个……
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(); }
有没有更好的方法将异常传递回ASP.net?
干杯,伊恩.
解决方法
任务将为您捕获例外情况.如果调用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(); }
简单地添加[HandleError]属性是不够的.由于异常发生在不同的线程中,我们必须将异常返回到ASP.NET线程,以便对它执行任何操作.只有在我们从正确的位置抛出异常之后,[HandleError]属性才能完成它的工作.