Solved

c# BackgroundWorker cancellation

Posted on 2010-08-18
9
585 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
Industry Leaders: 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!

 
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

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
VB.NET - Refactor Class per SOLID principles 2 33
IDE for Python 5 65
SSIS GUID Variable 2 31
.NET - find out if application is running on Windows 2012 server 3 32
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

735 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