【发布时间】:2015-03-09 21:38:54
【问题描述】:
我正在尝试使用 ContinueWith 和 OnlyOnFaulted 捕获从任务方法引发的异常,如下所示。但是,当我尝试运行此代码时,我得到了一个未处理的异常。
我希望任务运行完成,因为我已经处理了异常。但是 Task.Wait() 会遇到 AggregateException。
var taskAction = new Action(() =>
{
Thread.Sleep(1000);
Console.WriteLine("Task Waited for a sec");
throw (new Exception("throwing for example"));
});
Task t = Task.Factory.StartNew(taskAction);
t.ContinueWith(x => Console.WriteLine("In the on Faulted continue with code. Catched exception from the task."+ t.Exception), TaskContinuationOptions.OnlyOnFaulted);
Console.WriteLine("Main thread waiting for 4 sec");
Thread.Sleep(4000);
Console.WriteLine("Wait of 4 secs complete..checking if task is completed?");
Console.WriteLine("Task State: " + t.Status);
t.Wait();
如果我像下面这样在任务方法中处理异常,一切都会按我的预期进行。任务运行完成,异常被记录并且等待也成功。
var taskAction = new Action(() =>
{
try
{
Thread.Sleep(1000);
Console.WriteLine("Task Waited for a sec");
throw (new Exception("throwing for example"));
}
catch (Exception ex)
{
Console.WriteLine("Catching the exception in the Action catch block only");
}
});
Task t = Task.Factory.StartNew(taskAction);
t.ContinueWith(x=> Console.WriteLine("In the on Faulted continue with code. Catched exception from the task."+ t.Exception), TaskContinuationOptions.OnlyOnFaulted);
Console.WriteLine("Main thread waiting for 4 sec");
Thread.Sleep(4000);
Console.WriteLine("Wait of 4 secs complete..checking if task is completed?");
Console.WriteLine("Task State: " + t.Status);
t.Wait();
我的问题是:我是否正确使用了OnlyOnFaulted,还是在任务方法本身中处理异常总是更好?即使任务遇到异常,我也希望主线程继续。另外,我想从任务方法中记录该异常。
注意:我必须等待任务方法完成才能继续(有或没有错误)。
总结一下(我目前的理解)
如果来自 Task 的异常被处理,即如果 wait 或 await 捕获到异常,那么异常将被传播到 continuetask onfaulted。 即使在任务方法中也可以捕获异常并使用\处理。
try
{
t.wait();
}
catch(Exception e)
{
LogError(e);
}
在上述情况下,在调用 LogError 之前,与主任务的 onfaulted 关联的继续任务被执行。
【问题讨论】:
-
您使用的是哪个版本的 .NET 框架?
-
@YuvalItzchakov 使用 .NET 4.5。
标签: c# .net exception-handling task-parallel-library async-await