Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9196305
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T21:49:18+00:00 2026-06-17T21:49:18+00:00

How do I cancel all but the last/latest task? For example, suppose I have

  • 0

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?

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?

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

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

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

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

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

Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T21:49:19+00:00Added an answer on June 17, 2026 at 9:49 pm

    If you just want to cancel the last task, then that’s all you have to do:

    CancellationTokenSource cts = null;
    async void Button1_Click(...)
    {
      // Cancel the last task, if any.
      if (cts != null)
        cts.Cancel();
    
      // Create Cancellation Token for this task.
      cts = new CancellationTokenSource();
      var token = cts.Token;
    
      // Method to run asynchonously
      Func<int> taskAction = () =>
      {
        // Something time consuming
        Thread.Sleep(5000);
        token.ThrowIfCancellationRequested();
        return 100;
      };
    
      try
      {
        int i = await Task.Run(taskAction);
      }
      catch (OperationCanceledException)
      {
        // Don't need to do anything
        return;
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

When I click 'Cancel' from First page - it's ok. But 'Cancel' doesn't work
I have a cancel button in a form: @using (Html.BeginForm(ConfirmBid,Auction)) { some stuff ...
I have some code that adds mouseover events and mouseout events to all 'a'
Using cancelAllLocalNotifications should basically cancel the delivery of all scheduled local notifications . But
I have a widget that sets up a number of pendingIntents . All is
I have an asp:wizard control that contains five WizardSteps. All of these steps have
All, I've got the following code: var site_url = 'http://localhost/website/'; jQuery(#cancel_song_choice).click(function(event){ cancel_url = site_url
Possible Duplicate: Need to cancel click/mouseup events when double-click event detected Preventing double-click of
I have a screen that pops up on load with a print dialog using
I've looked at all these posts: jQuery stop fadein during fadeout jQuery stop "click"

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.