我正在尝试使用 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
正确还是在任务方法本身中处理异常总是更好?我希望即使任务遇到异常,主线程也能继续。另外,我想记录任务方法中的异常。
注意:我必须等待任务方法完成才能进一步(有或没有错误)。
总结一下(到目前为止我的理解)
如果处理来自任务的异常,即如果 wait 或 wait 捕获异常,则异常将传播到 onfaulted 的 continuetask。
即使在任务方法中也可以捕获异常并进行消费\处理。
try
{
t.wait();
}
catch(Exception e)
{
LogError(e);
}
在上述情况下,在调用 LogError 之前,将执行与主任务的 onfaulted 相关的连续任务。