How to stop the background worker while working

I am new to c sharp. I created a windows form application. my application is working fine. I want to cancel BackgroundWorker while working. I want to completely stop the BackgroundWorker process. I use this code to cancel the application, 1) first I used

    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {

        this.Dispose();
    }

but he does not stop. then i used

    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        bgBackfill1.CancelAsync();
        this.Dispose();
    }

but when I exit the application, it writes files to G: \ Drive. can someone tell me how can I stop writing files to G: \ Drive and complete the BackgroundWorker process completely.

Thanks if someone helps me.

+3
source share
4 answers

The desktop worker method must know that cancellation is expected, so only then can it cancel.

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;

    for (int i = 1; (i <= 10); i++)
    {
        if ((worker.CancellationPending == true))
        {
            e.Cancel = true;
            break;
        }
        else
        {
            // Perform a time consuming operation and report progress.
            System.Threading.Thread.Sleep(500);
            worker.ReportProgress((i * 10));
        }
    }
}

, CancelAsync, . DoWork - . . MSDN.

+5

"DoWork" ( worker1) employee1.CancellationPending, true, , , e.Cancel = true , .

+3

. :

 var bg= new BackgroundWorker();
 bg.WorkerSupportsCancellation = true;

CancellationPending BackgroundWorker, , .

+1

You must set the WorkerSupportsCancellation property when the component is initialized BackgroundWorkerand before the call RunWorkerAsync. So for example:

MyWorker = new BackgroundWorker();
MyWorker.WorkerSupportsCancellation = true;
MyWorker.WorkerReportsProgress = true;
MyWorker.DoWork += DoWorkEventHandler;
MyWorker.ProgressChanged += WorkerProgressChanged;
MyWorker.RunWorkerAsync();
+1
source

All Articles