开发者

Canceling a task when the main thread has exited

I have a main thread that starts a task but does not wait for its completion. I also have a cancel button on the UI, on the click of which I would like to cancel the task. I tried doing this at multiple places in the method in the task:

if (cancelToken.IsCancellationRequested)
                {
                    return;
                }

This however, does not seem to work in the desired way.

Earlier I thought of doing cancelToken.ThrowIfC开发者_JAVA技巧ancellationRequested() but as far as I understand, this raises an exception, and I have no place in the main thread to catch this. What would be the best way to cancel the task in this scenario?


Presumably your cancelToken originally came from a CancellationTokenSource which the main thread still has access to. You should just be able to call:

cancellationTokenSource.Cancel();

in your cancel button's click event handler.

ThrowIfCancellationRequested will throw an exception in the task thread, not in the main thread. You would only see an exception in the main thread if you called ThrowIfCancellationRequested and then requested the Result in the main thread.

Note that if you just return after cancellation has been requested, your task's state will end up as RanToCompletion rather than Canceled. Calling ThrowIfCancellationRequested is the preferred way of indicating cancellation, partly as it means if you've got a deep stack within your task's code, you don't need to worry about explicitly returning from each method.

I'm unsure whether cancellation represents a fault that needs to be observed, by the way - I suspect not, but you should probably check. (You should probably have a continuation to deal with errors anyway...)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜