2

Typically, when you are trying to do asynchronous tasks in a view-model, the code looks like so (simplified):

public class MyViewModel
{
    private CancellationTokenSource CTS { get; set; }

    public async Task Process()
    {
        CTS = new CancellationTokenSource();

        try
        {
            await LongRunningTask(CTS.Token);
        } catch (OperationCanceledException) { }
    }

    public async Task Cancel()
    {
        CTS.Cancel();
    }
}

The problem is that CancellationTokenSource is an IDisposable. Does that mean we simply place it in a using block, or is there something more to it since it is stored in a private property?

michael
  • 14,844
  • 28
  • 89
  • 177
  • 2
    Possible duplicate of [When to dispose CancellationTokenSource?](http://stackoverflow.com/questions/6960520/when-to-dispose-cancellationtokensource) – stuartd Jan 07 '16 at 17:02
  • 1
    Out of curiosity, if you call Process multiple times and then call Cancel, you'll be cancelling the _last_ task - is that what you want? Typically you'd call Cancel on the Task returned by the method call rather than having a separate Cancel method on your VM. – Brian Driscoll Jan 07 '16 at 17:03
  • 6
    Looks like `Process` should just accept a `CancellationToken` instead. – Servy Jan 07 '16 at 17:04
  • @BrianDriscoll What do you mean by *Typically you'd call Cancel on the Task returned by the method call rather than having a separate Cancel method on your VM.* `Task` doesn't have a `Cancel` method. Not sure what you mean here. – Sriram Sakthivel Jan 07 '16 at 17:20
  • @SriramSakthivel Yeah just ignore me on that one, looks like we added an extension method in our local library so it's not part of the TPL library. The extension method just calls Cancel on the token source. – Brian Driscoll Jan 07 '16 at 17:27

0 Answers0