asp.net-mvc-3 – 如何使用ASP.net MVC的AsyncController处理异常?

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – 如何使用ASP.net MVC的AsyncController处理异常?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个……
  1. public void FooAsync()
  2. {
  3. AsyncManager.OutstandingOperations.Increment();
  4.  
  5. Task.Factory.StartNew(() =>
  6. {
  7. try
  8. {
  9. doSomething.Start();
  10. }
  11. catch (Exception e)
  12. {
  13. AsyncManager.Parameters["exc"] = e;
  14. }
  15. finally
  16. {
  17. AsyncManager.OutstandingOperations.Decrement();
  18. }
  19. });
  20. }
  21.  
  22. public ActionResult FooCompleted(Exception exc)
  23. {
  24. if (exc != null)
  25. {
  26. throw exc;
  27. }
  28.  
  29. return View();
  30. }

有没有更好的方法将异常传递回ASP.net?

干杯,伊恩.

解决方法

任务将为您捕获例外情况.如果调用task.Wait(),它将在AggregateException中包装任何捕获的异常并抛出它.
  1. [HandleError]
  2. public void FooAsync()
  3. {
  4. AsyncManager.OutstandingOperations.Increment();
  5. AsyncManager.Parameters["task"] = Task.Factory.StartNew(() =>
  6. {
  7. try
  8. {
  9. DoSomething();
  10. }
  11. // no "catch" block. "Task" takes care of this for us.
  12. finally
  13. {
  14. AsyncManager.OutstandingOperations.Decrement();
  15. }
  16. });
  17. }
  18.  
  19. public ActionResult FooCompleted(Task task)
  20. {
  21. // Exception will be re-thrown here...
  22. task.Wait();
  23.  
  24. return View();
  25. }

简单地添加[HandleError]属性是不够的.由于异常发生在不同的线程中,我们必须将异常返回到ASP.NET线程,以便对它执行任何操作.只有在我们从正确的位置抛出异常之后,[HandleError]属性才能完成它的工作.

猜你在找的asp.Net相关文章