0

I have written a C# program to call a function through backgndWorkerEnroll_DoWork. It will start from a for shown event.

On the other side I have a button click event. When that event occurs I call a function and it it returns success, I want to close the backgroundworker.

How can I achieve this?

My code below.

private void PwdCheck_Shown(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

private void btnEnter_Click(object sender, EventArgs e)
{ 
    resPwdValid = PwdValid();
    if (resPwdValid == true)
    {
         //backgroundWorker1.CancelAsync();
         this.Close();
    }
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{               
    tstVerify:
        resVerify = testVerfy();
        if (resVerify == true)
        {
           // MessageBox.Show("Matched");
        }
        else
        {
           MessageBox.Show("Not Matched");
           goto tstVerify;
        }
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (resVerify == true)
    {
        this.Close();
    }
}

How can I close the backgroundrunner after my btnenter_click respwdvalid returns true?

Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151
Siva
  • 259
  • 6
  • 24

2 Answers2

0

Make use of the Cancellation Property

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
Chris Moutray
  • 18,029
  • 7
  • 45
  • 66
0

You would call BackgroundWorker.CancelAsync() I believe (you seem to have commented it out) and then in your DoWork code you should keep checking BackgroundWorker1.CancellationPending and exit your background thread early.

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
Ian
  • 160
  • 2
  • 9