Solved

c# BackgroundWorker cancellation

Posted on 2010-08-18
9
589 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
[X]
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
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
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 
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 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …
This video shows how to use Hyena, from SystemTools Software, to update 100 user accounts from an external text file. View in 1080p for best video quality.

752 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