Task does not wait for ContinueWith to finish

前端 未结 3 499
南旧
南旧 2021-01-19 16:42

I have console application and code as below,

My problem is before ContinueWith task finish, the console application ends, it does not waits the continueWith to fini

3条回答
  •  无人及你
    2021-01-19 17:26

    Jorge's solution is not working when an exception is thrown :

    var task = new Task(() =>
        {
            Console.WriteLine("My task...");
            throw new Exception();
        });
    
    task.Start();
    
    var taskNotOnFaulted = task.ContinueWith(t =>
    {
        Thread.Sleep(1000);
        Console.WriteLine("NotOnFaulted");
    }, TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.ExecuteSynchronously);
    var taskOnlyOnFaulted = task.ContinueWith(t =>
    {
        Thread.Sleep(1000);
        Console.Write("OnlyOnFaulted");
    }, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);
    
    Task.WaitAny(taskNotOnFaulted, taskOnlyOnFaulted);
    
    Console.WriteLine("Finished");
    

    The output is :

    My task...
    Finished
    OnlyOnFaulted
    

    This is because the taskNotOnFaulted get a Cancelled status when the exception is thrown, whereas it keeps a WaitingForActivation status when no exception is thrown.

    So you have to replace :

    Task.WaitAny(taskNotOnFaulted, taskOnlyOnFaulted);
    

    by

    if (task.IsFaulted)
        taskOnlyOnFaulted.Wait();
    else
        taskNotOnFaulted.Wait();
    

提交回复
热议问题