0

I am coding an OnAppearing method with a while loop and not sure how to do this with the Cancellation token. I have two example code blocks and I am not sure which would be best to use.

One uses the Token and the other does not. Can anyone tell me if there is any difference between the way the two will work and if I should be using one or the other and why?

    private CancellationTokenSource _ctsCards;

    public async Task OnAppearingAsync1()
    {
        _ctsCards = new CancellationTokenSource();
        var token = _ctsCards.Token;
        while (token.IsCancellationRequested == false)
        {
            await ShowCardAsync();
        }
    }

    public async Task OnAppearingAsync2()
    {
        _ctsCards = new CancellationTokenSource();
        while (_ctsCards.IsCancellationRequested == false)
        {
            await ShowCardAsync();
        }
    }

    public Stop() 
    {
        _ctsCards.Cancel()
    }
  • Isn't `OnAppearingAsync2` just gonna throw a NullReferenceException if you call it first? The Token is probably meant to be passed along to other API calls that are cancelable. – Jack T. Spades May 20 '21 at 03:03
  • I'd kind of expect that a `CancellationToken` should be passed to `OnAppearingAsync1`, and that something else would be responsible for the creation of the source. Maybe your code doesn't work like that though. – ProgrammingLlama May 20 '21 at 03:03
  • Thanks Jack, I didn't notice there was a line missing from that method and have just added it now. – Richard Scholey May 20 '21 at 03:05
  • If you use it like this, even a simple `bool` flag would do. As @Llama noted, `CancellationToken` is meant to be passed around to called functions so that cancellation can be performed also deeper down the call hierarchy. – Klaus Gütter May 20 '21 at 03:21
  • Thanks Klaus, I was also thinking about a simple bool flag but others had suggested I should be using a CancellationToken so that was confusing me as I didn't know why. – Richard Scholey May 20 '21 at 03:22
  • Do you _have_ to use the token? No. But is the API designed with the intent that you _will_ use the token? Yes. As a general rule, it would a poor implementation if you handed control over the cancellation itself to every piece of worker code that needed to be cancelled. By using the token instead, you retain control over if/when cancelling happens in the part of the code that actually _owns_ the cancellable work, instead of letting the cancellable work itself potentially signal a cancellation. See duplicate for more details. – Peter Duniho May 20 '21 at 06:55

0 Answers0