Waiting on a Task with a OnlyOnFaulted Continuation causes an AggregateException

后端 未结 1 1846
旧时难觅i
旧时难觅i 2021-02-03 18:50

I have some simple code as a repro:

var taskTest = Task.Factory.StartNew(() =>
{
    System.Threading.Thread.Sleep(5000);

}).ContinueWith((Task t) =>
{
           


        
1条回答
  •  暖寄归人
    2021-02-03 19:39

    You're not waiting on a task with an OnlyOnFaulted continuation - you're waiting on that continuation (returned by ContinueWith). The continuation is never going to fire because the original task returned normally, so it's acting as if it were cancelled.

    Makes sense to me.

    I suspect you want to create the task, add the continuation, but then wait on the original task:

    var taskTest = Task.Factory.StartNew(() =>
    {
        System.Threading.Thread.Sleep(5000);
    
    });
    taskTest.ContinueWith((Task t) =>
    {
        Console.WriteLine("ERR");
    }, TaskContinuationOptions.OnlyOnFaulted);
    

    0 讨论(0)
提交回复
热议问题