JeffreyZhao/wind

about task cancellation

Closed this issue · 1 comments

I feel that using a cancellation token to cancel a task makes code more complex, since we have the burden to manage task concellation tokens. I prefer adding two methods cancel() and is_cancelling to task object, and do not throw exception while cancelling (sometimes cancel is not an exception or error, it's a normal opeation, so throw exceptions might be unexpected).

For example, in an async task, I wish to write:

var foo_task = eval(Jscex.compile("async", functoin() {

    var task1 = Task1(), task2 = Task2();

    task1.start(); task2.start();

    while( true ) {
        $await(some_kind_of_event_for_example_a_timer());

        /* it might be convenient to use $task as the reference to the current task?
           thus I can write:
           if( $task.is_cancelling() )
        */
        if( this_task.is_cancelling() )
        {
            task1.cancel(); task2.cancel();

            /*
                task1 and task2 check the cancelling and then quit
            */

            $await(task1, task2);

            break;
        }
    }
}));

I think this is simple and clean, what's your opinion?

Use CancellationToken is to have a chance to cancel a collection of tasks. We can maintain a single cancellation token and start multiple tasks as required, then cancel all the tasks if we need. The token can also be passed to another task from a task. Further, not all the tasks can be canceled, so a token represents the "cancel-bility" of the task.

And treat cancel as an exception makes it easy to spread the cancellation from child tasks to parents. Exceptions doesn't means error it's just an "non-ordinary" situation.

If you still have questions I can give you more details, maybe in a blog post.