C# 如何正确处理后台任务中的异常?
假设我有一个ASP.NETWebAPI项目 在调用HomeController中的一个操作后,我在后台启动新任务,并立即返回响应。它看起来像这样:C# 如何正确处理后台任务中的异常?,c#,asp.net,.net,task,task-parallel-library,C#,Asp.net,.net,Task,Task Parallel Library,假设我有一个ASP.NETWebAPI项目 在调用HomeController中的一个操作后,我在后台启动新任务,并立即返回响应。它看起来像这样: public ActionResult Test(int id) { Task.Run(() => .... someMethod); return new SomeViewModel(); } 正如你们所看到的,我不是在等待任务的完成,它完全是背景工作 在my global.asax中,我捕获项目中所有未处理的异常。但是,
public ActionResult Test(int id)
{
Task.Run(() => .... someMethod);
return new SomeViewModel();
}
正如你们所看到的,我不是在等待任务的完成,它完全是背景工作 在my global.asax中,我捕获项目中所有未处理的异常。但是,当在Task.Run中调用我的someMethod时抛出异常,ASP中的应用程序错误事件不会捕获它。为什么?如何正确处理后台任务中的所有异常?根据这一点,您可以通过查询任务的Exception属性来检查任务中的异常。以下是从参考中提取的代码:
using System;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
var task1 = Task.Run( () => { throw new CustomException("This exception is expected!"); } );
while(! task1.IsCompleted) {}
if (task1.Status == TaskStatus.Faulted) {
foreach (var e in task1.Exception.InnerExceptions) {
// Handle the custom exception.
if (e is CustomException) {
Console.WriteLine(e.Message);
}
// Rethrow any other exception.
else {
throw e;
}
}
}
}
}
public class CustomException : Exception
{
public CustomException(String message) : base(message)
{}
}
// The example displays the following output:
// This exception is expected!
请注意,保存任务的变量的作用域已充分持久化,因此可以查询其Exception属性。您的示例中有一个隐式的本地存储任务,当执行返回时,该任务将不在范围内
--ss您得到了什么例外?请注意,ASP.Net强烈反对您的方法。这不仅是为了处理异常,还因为您的任务随时可能被IIS中断。查看了解更多信息。“正如你们所看到的,我并不是在等待任务的完成,这完全是背景工作。”。如果他们真的想在返回之前等待任务完成,他们可以在
task.wait()
周围包装一个try/catch,并在没有所有这些额外代码的情况下捕获异常。但这不是他们所要求的。任务必须持久化在一个变量中,可能是类范围的变量,该变量将允许查询TaskFaulted和Exception属性。