Who canceled my Task?

2019-03-15 23:09发布

My C# Task is getting canceled, but not by me. I don't get a stacktrace and I can't figure out where the problem occurs.

My task invocation looks like this:

var t = Task<Boolean>.Factory.StartNew(() =>
    {
        Boolean bOk = DoSomthingImportant();
        return bOk;
    }, TaskCreationOptions.AttachedToParent)
    .ContinueWith<Boolean>((theTask) =>
    {
        var reason = theTask.IsCanceled ? "it was canceled" : "it faulted";
        Debug.WriteLine("Error: Task ended because " + reason + ".");
        ... log the exception to one of my objects...
        return false;
    }, TaskContinuationOptions.NotOnRanToCompletion);

I want the continuation task to run if the task faulted or was canceled, but not if it ran okay. The continuation is never executed.

Later on my program catches an AggregateException which is wrapping a TaskCanceledException.

My other major interaction with my tasks is to call WaitAny(taskArray, timeout) until I have no more tasks to start, then call WaitAll with no timeout until the last task is done.

Could WaitAny with a timeout cause a cancellation? Why didn't my continuation get called?

This is only my second brush with the Task library, so I am clueless.

UPDATE:

I found this SO question: How to propagate a Task's Canceled status to a continuation task. One error in my code above (but not the cause of the Cancelation) is that I assumed that the Continuation tasks status was the same as the original task's status. In fact you have to do some work to get the one from the other, as the other post describes.

UPDATE 2:

Brian: Thanks for the documentaion reference. I had searched high and low for alternate causes of a Task being canceled, but missed these words:

"If you are waiting on a Task that transitions to the Canceled state, a Task (wrapped in an AggregateException) is manufactured and thrown. Note that this exception indicates successful cancellation instead of a faulty situation. Therefore, the Task's Exception property returns null."

1条回答
劳资没心,怎么记你
2楼-- · 2019-03-16 00:11

You're waiting on the continuation and since the original task ran to completion the continuation task was cancelled. This behavior is covered in the documentation.

查看更多
登录 后发表回答