Cancel all but last task
<p>How do I cancel all but the last/latest task? For example, suppose I have a time-consuming task that is triggered on a button click. I only want the task from the last button click to run and the previous ones to cancel. Can you show me how this is normally done?</p>

<p>My attempt involves storing all tasks in a list along with their cancellation token and removing them when either the task completes or is cancelled. Creating a list to store both Task and CancellationToken seems like I'm doing too much for what I would've thought is a common requirement (eg. a User does a search for something and clicks the search button multiple times. Shouldn't only the last search be made and all other cancelled?). This is a common scenario, so I'd like to know how this is normally done. What is best practice here?</p>

<pre><code>async void DoStuffAsync()
{
    // Store tasks in a list
    if (tasksAndCancelTokens == null)
        tasksAndCancelTokens = new List&lt;Tuple&lt;Task, CancellationTokenSource&gt;&gt;();
    else // we have a new Get request so cancel any previous
        tasksAndCancelTokens.ForEach(t =&gt; t.Item2.Cancel());

    // Create Cancellation Token
    var cts = new CancellationTokenSource();

    // Method to run asynchonously
    Func&lt;int&gt; taskAction = () =&gt;
    {
        // Something time consuming
        Thread.Sleep(5000);
        if (cts.Token.IsCancellationRequested)
           cts.Token.ThrowIfCancellationRequested();
        return 100;
    };

    // Create Task
    Task&lt;int&gt; task = Task&lt;int&gt;.Factory.StartNew(taskAction, cts.Token);
    // Create Tuple to store task in list
    var tup = new Tuple&lt;Task, CancellationTokenSource&gt;(task, cts);
    tasksAndCancelTokens.Add(tup);

    try
    {
        int i = await task;
    }
    catch (OperationCanceledException)
    {
        // Don't need to do anything
    }
    finally
    {
        tasksAndCancelTokens.Remove(tup);
    }
}
</code></pre>

<p>Thanks</p>
