0

My code declares a cancellation token here in a view model, creates it in the OnAppearing and Cancels in the OnDisappearing:

public partial class DeckTabViewModel : BaseViewModel
{
    public CancellationTokenSource cts;
}

Then in OnAppearing:

public partial class DeckTabViewModel : BaseViewModel
{
    public async Task OnAppearingAsync()
    {
        cts = new CancellationTokenSource();
        await GetCards(cts.Token);
    }
}

And on Disappearing:

public partial class DeckTabViewModel : BaseViewModel
{
    public async Task OnDisappearingAsync()
    {
       cts.Cancel();
    }
}

Could someone tell me if this is the correct way to use the Cancellation token and should I in the OnDisappearing, also set it to null?

Oliver
  • 926
  • 2
  • 12
  • 31
Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427
  • Does this answer your question? [When to dispose CancellationTokenSource?](https://stackoverflow.com/questions/6960520/when-to-dispose-cancellationtokensource) – FreakyAli Feb 09 '20 at 18:29

1 Answers1

0

As CancellationTokenSource implements IDisposable, you should dispose the instance of CancellationTokenSource (in your example, cts) when you have finished using it: you can do so directly by calling the Dispose method, or indirectly using the using construct.

In your case, you would call Dispose after calling Cancel on cts:

public partial class DeckTabViewModel : BaseViewModel
{
    public async Task OnDisappearingAsync()
    {
        try
        {
            cts.Cancel();
        }
        finally
        {
             if(cts != null)
             {
                 cts.Dispose();
             }
        }
    }
}
Oliver
  • 926
  • 2
  • 12
  • 31