gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:24:36 25 4
gpt4 key购买 nike

我有这个...

    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将为您捕获异常。如果您调用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]属性能够完成它的工作。

关于asp.net-mvc-3 - 您如何使用 ASP.net MVC 的 AsyncController 处理异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6171273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com