在连续链中传播异常的正确方法是什么?

ron*_*nag 13 c# exception task task-parallel-library continuation

在连续链中传播异常的正确方法是什么?

t.ContinueWith(t2 => 
{
     if(t2.Exception != null)
         throw t2.Exception;

     /* Other async code. */
})
.ContinueWith(/*...*/);   

t.ContinueWith(t2 => 
{
     if(t2.IsFaulted)
         throw t2.Exception;

     /* Other async code. */
})
.ContinueWith(/*...*/);

t.ContinueWith(t2 => 
{
     if(t2.Exception != null)
         return t2;

     /* Other async code. */
})
.ContinueWith(/*...*/);   

t.ContinueWith(t2 => 
{
     if(t2.IsFaulted)
         return t2;

     /* Other async code. */
})
.ContinueWith(/*...*/);


t.ContinueWith(t2 => 
{
     t2.Wait();

     /* Other async code. */
})
.ContinueWith(/*...*/);

t.ContinueWith(t2 => 
{     
     /* Other async code. */
}, TaskContinuationOptions.NotOnFaulted) // Don't think this one works as expected
.ContinueWith(/*...*/);
Run Code Online (Sandbox Code Playgroud)

Ser*_*rvy 1

如果您不想在发生异常时执行任何操作(即记录日志),而只想传播异常,那么在抛出异常时(或取消事件时)不要运行延续。

task.ContinueWith(t =>
{
    //do stuff
}, TaskContinuationOptions.OnlyOnRanToCompletion);
Run Code Online (Sandbox Code Playgroud)

如果您明确想要处理异常的情况(也许要进行日志记录,将引发的异常更改为其他类型的异常(可能带有附加信息,或者隐藏不应公开的信息)),那么您可以添加选项的延续OnlyOnFaulted(可能除了正常情况的延续之外)。