How to cancel a CancellationToken

前端 未结 4 1730
我在风中等你
我在风中等你 2021-02-06 20:30

I start a task, that start other tasks and so forth.
Given that tree, if any task fails the result of the whole operation is useless. I\'m considering using cancellation tok

相关标签:
4条回答
  • 2021-02-06 20:56

    A token it gives you the right to know someone is trying to cancel something. It does not give you the right to actually signal a cancellation. Only the cancellation token source gives you that. This is by design.

    0 讨论(0)
  • 2021-02-06 20:58

    As an extension of the answers provided so far, if you want to have both a CancellationToken instance provided to your methods, and cancel internally, you should examine CancellationTokenSource.CreateLinkedTokenSource. In essence this will cancel either when cts.Cancel() is called, or one of its supplied tokens is.

    0 讨论(0)
  • 2021-02-06 21:13

    As the docs state you need to call the cancel method from the source object. Example code is included in the link you provided. Here are the relevant sections:

    // Define the cancellation token.
    CancellationTokenSource source = new CancellationTokenSource();
    previouslyProvidedToken = source.Token;
    ...
    source.Cancel();
    

    CancellationToken Struct

    how can I, in possession of ONLY a CancellationToken, cancel it?

    Without a reference to the source you cannot cancel a token. That doesn't mean that you need the CancellationTokenSource that first spawned the token. When given a CancellationToken, you can create a new instance of token source assign it's token to the provided token and cancel it. All other parties that can read this token will see that it's cancellation has been requested.

    0 讨论(0)
  • 2021-02-06 21:20

    Spawn CancellationToken instances from a CancellationTokenSource instance and call Cancel on the CTS instance.

    Example: https://msdn.microsoft.com/en-us/library/dd321955(v=vs.110).aspx

    There's also a way to gracefully cancel threads without them firing exceptions, just check the CT for IsCancellationRequested and handle the case yourself. More info: Use of IsCancellationRequested property?

    0 讨论(0)
提交回复
热议问题