继续任务如何捕获返回 void 的 C# 任务的异常



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 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());

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;
                        });
            });

找到了答案——

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());

最新更新