ContinueWith任务如何捕获返回void的C#任务的异常?

时间:2015-01-25 19:43:27

标签: c# asynchronous task

ContinueWith任务如何捕获返回void的C#异步任务的异常? (我们正在使用VS 2010,因此还没有async / await关键字)。任务返回时我们的标准模式是:

Task<int> task = ...;
task.ContinueWith(t =>
{
   try
   {
      int result = task.Result; //This will throw if there was an error.
      //Otherwise keep processing
   }
   catch(Exception e)
   { ... }
}, TaskScheduler.FromCurrentSynchronizationContext());

但如果任务没有返回任何内容,则没有“task.Result”。那么处理那些不返回任务的任务的最佳方法是什么呢?

编辑:这是我想要完成的事情:

Task taskWithNoReturnType = ...
taskWithNoReturnType.ContinueWith( t =>
{
   try
   {
      //HOW CAN I KNOW IF THERE WAS AN EXCEPTION ON THAT TASK???

      //Otherwise, keep processing this callback
   }
   catch(Exception e)
   { ... }
}, TaskScheduler.FromCurrentSynchronizationContext());

2 个答案:

答案 0 :(得分:3)

Task.Exception获取导致任务过早结束的AggregateException。如果任务成功完成或尚未抛出任何异常,则返回null。

示例:

Task.Factory
       .StartNew(
            () => { DoSomething(); /* throws an exception */ } )
       .ContinueWith(
            p =>
            {
                if (p.Exception != null)
                    p.Exception.Handle(x =>
                        {
                            Console.WriteLine(x.Message);
                            return true;
                        });
            });

答案 1 :(得分:1)

找到答案 -

Task taskWithNoReturnType = ...
taskWithNoReturnType.ContinueWith( t =>
{
   try
   {
      t.Wait(); //This is the key. The task has already completed (we 
      //are in the .ContinueWith() after all) so this won't really wait,
      //but it will force any pending exceptions to propogate up and 
      //then the catch will work normally. 

      //Else, if we get here, then there was no exception.
      //<process code normally here>
   }
   catch(Exception e)
   { ... }
}, TaskScheduler.FromCurrentSynchronizationContext());