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

  • Home
  • SEARCH
  • 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 6584651
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T16:33:47+00:00 2026-05-25T16:33:47+00:00

I have a method processData() that takes a large amount of data and does

  • 0

I have a method processData() that takes a large amount of data and does some work on it. There’s a start button that initiates the processing. I need a cancel button that stops the processing wherever it’s at. How can I implement something like that? The thing I don’t get is how to make the cancel button usable once the processing has started since the rest of the UI is frozen when the function is running.

  • 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-25T16:33:48+00:00Added an answer on May 25, 2026 at 4:33 pm

    BackgroundWorker.CancelAsync Method is what you need. Here is a good example for you.

    If you have got a time consuming process you will have to use a separate thread to handle that in order to support for cancellation. If you execute that time consuming process in the main thread(UI thread) it will be busy and won’t take your cancellation request in to account until it finish that task. That’s why you experience UI freezing.

    If you use a backgroundWorker for your time consuming task and if you check the CancellationPending flag in the BackgroundWorker.DoWork method you could achieve what you want.

    using System;  
    using System.Collections.Generic;  
    using System.ComponentModel;  
    using System.Data;  
    using System.Drawing;  
    using System.Text;  
    using System.Windows.Forms;  
    
    namespace BackgroundWorker  
    {  
        public partial class Form1 : Form  
        {  
            public Form1()  
            {  
                InitializeComponent();  
    
                //mandatory. Otherwise will throw an exception when calling ReportProgress method  
                backgroundWorker1.WorkerReportsProgress = true;   
    
                //mandatory. Otherwise we would get an InvalidOperationException when trying to cancel the operation  
                backgroundWorker1.WorkerSupportsCancellation = true;  
            }  
    
            //This method is executed in a separate thread created by the background worker.  
            //so don't try to access any UI controls here!! (unless you use a delegate to do it)  
            //this attribute will prevent the debugger to stop here if any exception is raised.  
            //[System.Diagnostics.DebuggerNonUserCodeAttribute()]  
            private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)  
            {  
                //NOTE: we shouldn't use a try catch block here (unless you rethrow the exception)  
                //the backgroundworker will be able to detect any exception on this code.  
                //if any exception is produced, it will be available to you on   
                //the RunWorkerCompletedEventArgs object, method backgroundWorker1_RunWorkerCompleted  
                //try  
                //{  
                    DateTime start = DateTime.Now;  
                    e.Result = "";  
                    for (int i = 0; i < 100; i++)  
                    {  
                        System.Threading.Thread.Sleep(50); //do some intense task here.  
                        backgroundWorker1.ReportProgress(i, DateTime.Now); //notify progress to main thread. We also pass time information in UserState to cover this property in the example.  
                        //Error handling: uncomment this code if you want to test how an exception is handled by the background worker.  
                        //also uncomment the mentioned attribute above to it doesn't stop in the debugger.  
                        //if (i == 34)  
                        //    throw new Exception("something wrong here!!");  
    
                        //if cancellation is pending, cancel work.  
                        if (backgroundWorker1.CancellationPending)  
                        {  
                            e.Cancel = true;   
                            return;  
                        }  
                    }  
    
                    TimeSpan duration = DateTime.Now - start;  
    
                    //we could return some useful information here, like calculation output, number of items affected, etc.. to the main thread.  
                    e.Result = "Duration: " + duration.TotalMilliseconds.ToString() + " ms.";  
                //}  
                //catch(Exception ex){  
                //    MessageBox.Show("Don't use try catch here, let the backgroundworker handle it for you!");  
                //}  
            }  
    
            //This event is raised on the main thread.  
            //It is safe to access UI controls here.  
            private void backgroundWorker1_ProgressChanged(object sender,   
                ProgressChangedEventArgs e)  
            {  
                progressBar1.Value = e.ProgressPercentage; //update progress bar  
    
                DateTime time = Convert.ToDateTime(e.UserState); //get additional information about progress  
    
                //in this example, we log that optional additional info to textbox  
                txtOutput.AppendText(time.ToLongTimeString());  
                txtOutput.AppendText(Environment.NewLine);              
            }  
    
            //This is executed after the task is complete whatever the task has completed: a) sucessfully, b) with error c)has been cancelled  
            private void backgroundWorker1_RunWorkerCompleted(object sender,   
                RunWorkerCompletedEventArgs e)  
            {  
                if (e.Cancelled) {  
                    MessageBox.Show("The task has been cancelled");  
                }  
                else if (e.Error != null)  
                {                  
                    MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString());  
                }  
                else {  
                    MessageBox.Show("The task has been completed. Results: " + e.Result.ToString());  
                }  
    
            }  
    
            private void btoCancel_Click(object sender, EventArgs e)  
            {  
                //notify background worker we want to cancel the operation.  
                //this code doesn't actually cancel or kill the thread that is executing the job.  
                backgroundWorker1.CancelAsync();  
            }  
    
            private void btoStart_Click(object sender, EventArgs e)  
            {  
                backgroundWorker1.RunWorkerAsync();  
            }  
        }  
    }  
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a method that takes an IQueryable. Is there a LINQ query that
I have a method that takes a cgi object and creates a CGI::FormBuilder object.
I have method that transforms some input value by the user passing it a
I have method in a class that I need to make sure is only
I have a method which takes params object[] such as: void Foo(params object[] items)
I have class method that returns a list of employees that I can iterate
I have a method that where I want to redirect the user back to
I have a method in my Python code that returns a tuple - a
I have a method that can return either a single object or a collection
I have this method on a webpart: private IFilterData _filterData = null; [ConnectionConsumer(Filter Data

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.