Usage of Cancellation Token

橙三吉。 提交于 2019-12-02 01:20:32

The quote you added was related to creating a new Task via Task.Run or Task.Factory.Startnew. When passing a CancellationToken to your method, you have to actively check the token before running

private async Task CheckMeCalled(CancellationToken ct)
{
    ct.ThrowIfCancellationRequested();
    Debug.WriteLine("Before task delayed".ToUpper());
    await Task.Delay(5000, ct);
    Debug.WriteLine("After task delayed".ToUpper());
}

Here is a quote by Stephan Toub regarding cancellation token and Task:

If the token has cancellation requested prior to the Task starting to execute, the Task won't execute. Rather than transitioning to Running, it'll immediately transition to Canceled. This avoids the costs of running the task if it would just be canceled while running anyway.

I also recommend reading NET 4 Cancellation Framework for a broad review of the cancellation mechanism by the PFX Team

You have to manually check the token to see if a cancellation was requested.

With:

ct.IsCancellationRequested
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!