Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

c# BackgroundWorker cancellation

Posted on 2010-08-18
9
577 Views
Last Modified: 2013-12-17
Morning all!

Dilemma:
I have a backgroundworker which does a lot of work. Basically it pulls off a massive SQL function and then runs a while loop for every row doing man different things such as creating AD accounts, mailboxes home drives etc.

I need a button which starts the backgroundworker and then when clicked again cancels it. I have tried everything, but it just doesn't work...


help :)



private void btn_startSync_Click_1(object sender, EventArgs e)
        {

            if (bg_worker.IsBusy != true)
            {
                lbl_status.Text = "Status: Started";
                lbl_status_main.Text = "Started";
                bg_worker.RunWorkerAsync();
            }

            else if (bg_worker.WorkerSupportsCancellation == true && bg_worker.IsBusy == true)
            {
                bg_worker.CancelAsync();
                lbl_status.Text = "Status: Stopped";
                lbl_status_main.Text = "Stopped";
            }
 
        }

Open in new window

0
Comment
Question by:KazooSoft
9 Comments
 
LVL 42

Accepted Solution

by:
sedgwick earned 500 total points
ID: 33462348
0
 
LVL 7

Expert Comment

by:Gene_Cyp
ID: 33462359
Can you show your code inside the three background worker handlers please?
 
0
 
LVL 3

Expert Comment

by:sathisemail
ID: 33462406
Hi,
   In bg_worker_DoWork method, you need to check whether bg_worker.CancellationPending is true and if so, you need to break the loop in the method. This should solve your problem.

0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
LVL 42

Expert Comment

by:sedgwick
ID: 33462432
i've attached the event handler of the backgournworker.
once u call backgroundWorker.CancelAsync(), the loop while(!backgroundWorker.CancellationPending) is skipped and next thing it check if(backgroundWorker.CancellationPending).
static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
  BackgroundWorker backgroundWorker = sender as BackgroundWorker;
  if(backgroundWorker != null)
  {
    backgroundWorker.ReportProgress(0); // report start

    int percentProgress = 1;
    while(!backgroundWorker.CancellationPending)
    {
      // TODO: Unit of work.
      // TODO: update percentProgress
      backgroundWorker.ReportProgress(precentProgress);
    }
    // TODO: update e.Result with result, if required.

    // provide feedback to the other thread that the
    // cancellation was processed
    if(backgroundWorker.CancellationPending)
    {
      e.Cancel = true;
    }
    else
    {
      // report end of processing
      backgroundWorker.ReportProgress(100);
    }
  }
}

Open in new window

0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 33462676
your code has to be in a loop somewhere and this loop needds to check for cancellation. check http://www.emoreau.com/Entries/Articles/2006/12/The-BackgroundWorker-component.aspx
0
 
LVL 4

Author Comment

by:KazooSoft
ID: 33463404
When I follow what you have all put I get an error when trying to stop it:

Exception has been thrown by the target of an invocation

But when I remove this code:

// TODO: update e.Result with result, if required.

                        // provide feedback to the other thread that the
                        // cancellation was processed
                        if (bg_worker.CancellationPending)
                        {
                            e.Cancel = true;
                            Log_Action("Done!", 2);
                        }
                        else
                        {
                            // report end of processing
                            bg_worker.ReportProgress(100);
                            Log_Action("Done!", 2);
                        }

It works fine...

Why?


0
 
LVL 42

Expert Comment

by:sedgwick
ID: 33463416
which line triggers this error?
0
 
LVL 4

Author Comment

by:KazooSoft
ID: 33463428
Found the problem which was causing that error:

Is is the commented line in the below code
        // What to do once the background worker has finnished
        private void bg_worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btn_startSync.Enabled = true;
            lbl_status.Text = "Status: Finished";
            lbl_status_main.Text = "Finished";
            //String result = e.Result as String;            
        }

Open in new window

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 33466703
In RunWorkerCompleted() you should check the "e.Cancelled" paremeter:
        // What to do once the background worker has finnished
        private void bg_worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btn_startSync.Enabled = true;
            if (!e.Cancelled) {
                lbl_status.Text = "Status: Finished";
                lbl_status_main.Text = "Finished";
                String result = e.Result as String;            
                // do something with "result"
            }
            else {
                lbl_status.Text = "Status: Cancelled";
                lbl_status_main.Text = "Cancelled";
            }
        }

Open in new window

0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…

861 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question