How To Start And Stop A Continuously Running Background Worker Using A Button

后端 未结 5 2197
春和景丽
春和景丽 2020-12-01 22:10

Let\'s say I have a background worker like this:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
             while(true)
          


        
5条回答
  •  孤城傲影
    2020-12-01 23:10

    By stop do you really mean stop or do you mean pause? If you mean stop, then this is a piece of cake. Create a button click event handler for the button you want to be responsible for starting the background worker and a button click event handler for the one responsible for stopping it. On your start button, make a call to the background worker method that fires the do_work event. Something like this:

    private void startButton_Click(System.Object sender, 
        System.EventArgs e)
    {
        // Start the asynchronous operation.
        backgroundWorker1.RunWorkerAsync();
    }
    

    On your stop button, make a call to the method that sets the background worker's CancellationPending to true, like this:

    private void cancelAsyncButton_Click(System.Object sender, 
        System.EventArgs e)
    {   
        // Cancel the asynchronous operation.
        this.backgroundWorker1.CancelAsync();
    }
    

    Now don't forget to check for the CancelationPending flag inside your background worker's doWork. Something like this:

       private void KillZombies(BackgroundWorker worker, DoWorkEventArgs e)
       {
            while (true)
            {
                if (worker.CancellationPending)
               {   
                  e.Cancel = true;
               }
            }
       }
    

    And your doWork method:

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
            {
                 BackgroundWorker worker = sender as BackgroundWorker;
                 KillZombies(worker, e);
            }
    

    I hope this can steer you in the right direction. Some further readings:

    http://msdn.microsoft.com/en-us/library/b2zk6580(v=VS.90).aspx

    http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

    http://msdn.microsoft.com/en-us/library/waw3xexc.aspx

提交回复
热议问题