Solved

c# BackgroundWorker cancellation

Posted on 2010-08-18
9
555 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
 
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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 69

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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

757 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now