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 7564099
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T13:49:51+00:00 2026-05-30T13:49:51+00:00

Consider an asynchronous operation like obtaining search results from a data storage. Now I

  • 0

Consider an asynchronous operation like obtaining search results from a data storage. Now I want it to be possible, to cancel a currently pending search operation, to start a new one, that in fact replaces the active search, mostly because the search parameters changed meanwhile.

My search is started via TPL (.NET 4.0) new Task and eventually has Continues and of course has callbacks, that invoke UI-Methods on UI-Context.

So, if the search button is pressed again, while search tast is running, I firstly have to stop current task and wait for it to end. If I do that from UI thread, I may run into a deadlock, since Wait() on UI thread blocks it, so a possible Invoke() will never execute.

Therefore, in my current solution, I start a separate task, which waits for running tasks to end/abort and then runs the new ones. This feels a bit bulky and cumbersome and I wonder, if there ain’t no more elegant way, since I need this kind of mechanism frequently.

So am I maybe missing a framework mechanism that’s usable for this kind of scenario? Or what would be a more recommended way?

  • 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-05-30T13:49:52+00:00Added an answer on May 30, 2026 at 1:49 pm

    I believe this is what you are looking for. I have commented the code so most of the reasoning is embedded in the code.

    Basically, have your continue functions deal with spinning up a prepped Task.

    Task currentTask;
    CancellationTokenSource cancelTokenSource;
    CancellationToken cancelToken;
    Task newTask;
    CancellationTokenSource newCancelTokenSource;
    CancellationToken newCancelToken;
    
    public Form1()
    {
        InitializeComponent();
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
        if(currentTask != null && currentTask.Status == TaskStatus.Running)
        {
            //Cancel the running task
            cancelTokenSource.Cancel();
            //Prepare a new Task to be triggered when the other cancels
            //You could store new tasks/tokens in a dictionary if you wanted,also
            //A new cancel token is always needed since the old stays cancelled
            newCancelTokenSource = new CancellationTokenSource();
            newCancelToken = newCancelTokenSource.Token;
            newTask = new Task(()=>LongRunningTask(), newCancelToken);
    
            //Continue that deals with both cancel and completion
            //There is a different way to deal with this below, also
            newTask.ContinueWith((previousTask)=>
            {
                if(previousTask.Status == TaskStatus.Cancelled)
                {
                    label1.Text = "New Task Cancelled, Another New Starting";
                    BeginNewTask();
                }
                else
                    label1.Text = "New Task Ran To Completion";
            },
            //If cancelled token is passed, it will autoskip the continue
            new CancellationTokenSource().Token, TaskContinuationOptions.None,
            //This is to auto invoke the UI thread
            TaskScheduler.FromCurrentSynchronizationContext());
        }
        else
        {
            cancelTokenSource = new CancellationTokenSource();
            cancelToken = cancelTokenSource.Token;
            //Start a fresh task since none running
            currentTask = Task.Factory.StartNew(()=>LongRunningTask(), 
                cancelToken);
    
            //OnCancelContinue
            currentTask.ContinueWith((previousTask)=>
            {
                label1.Text = "First Task Cancelled, New Starting";
                BeginNewTask();
            },
            //If cancelled token is passed, it will autoskip the continue
            new CancellationTokenSource().Token, 
            TaskContinuationOptions.OnlyOnCancelled,
            //This is to auto invoke the UI thread
            TaskScheduler.FromCurrentSynchronizationContext());
    
            //OnCompleteContinue
            currentTask.ContinueWith((previousTask)=>
            {
                label1.Text = "First Task Ran To Completion";
            },
            //If cancelled token is passed, it will autoskip the continue
            new CancellationTokenSource().Token, 
            TaskContinuationOptions.OnlyOnRanToCompletion,
            //This is to auto invoke the UI thread
            TaskScheduler.FromCurrentSynchronizationContext());
        }
    }
    
    private void LongRunningTask()
    {
         for(int i = 0; i < 60; i++)
         {
             if(cancelToken.IsCancellationRequested)
                 cancelToken.ThrowIfCancellationRequested();
             Thread.Sleep(1000);
         }
    }
    
    private void BeginNewTask()
    {
        //Since the old task is cancelled, reset it with the new one
        //Probably should do some error checks
        currentTask = newTask;
        cancelTokenSource = newCancelTokenSource;
        cancelToken = newCancelToken;
        //This is to make sure this task does not run on the UI thread
        currentTask.Start(TaskScheduler.Default);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Consider me rusty on the subject of asynchronous delegates. If I want to call
Consider the Oracle emp table. I'd like to get the employees with the top
Consider 3 regex expressions designed to remove non Latin characters from the string. String
I still consider myself a beginner when it comes to JQUERY+Coldfusion...so I'd like to
I have a page which is fetching data from a webservice using async call.
Consider the following example quoted from php manual for DateTime <?php $date = new
I'm currently working on a largely asynchronous application which uses TAP throughout. Every class
I would like to parameterize a type with one of its subclasses. Consider the
Consider the following setup: A windows PC with a LAN interface and a WiFi
Consider the need to develop a lightweight desktop DB application on the Microsoft platforms.

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.