Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

c# BackgroundWorker cancellation

Posted on 2010-08-18
9
Medium Priority
?
604 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:
Meir Rivkin earned 2000 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
Nothing ever in the clear!

This technical paper will help you implement VMware’s VM encryption as well as implement Veeam encryption which together will achieve the nothing ever in the clear goal. If a bad guy steals VMs, backups or traffic they get nothing.

 
LVL 42

Expert Comment

by:Meir Rivkin
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:Meir Rivkin
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 86

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 learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

Question has a verified solution.

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

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
Screencast - Getting to Know the Pipeline
Suggested Courses

773 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