oimitro
oimitro

Reputation: 1506

C# BackgroundWorker Wait Until Ends

I'm working in a projects that needs to be done with a thread.

I have a background worker that does the job. What I want to accomplish is when I hit Button3, my background worker will restart. I have already tried to wait for background worker to finish with Backgroundworker1.IsBusy in a while, but this never ends. When I hit Button3, I get the error

This BackgroundWorker is currently busy and cannot run multiple tasks concurrently

This is my code:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

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

    private void button2_Click(object sender, EventArgs e)
    {
        backgroundWorker1.CancelAsync();
    }

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

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;
        int x = 0, y = 0, result;

        while (true)
        {
            if (backgroundWorker1.CancellationPending)
            {
                e.Cancel = true;
                break;
            }
            else
            {
                x++;
                y++;
                result = x + y;
                this.label1.Invoke(new MethodInvoker(() => this.label1.Text =     result.ToString()));
            }
        }
    }

}//public partial class Form1 : Form

Upvotes: 1

Views: 517

Answers (2)

jeremywho
jeremywho

Reputation: 309

The background worker hasn't completed before the RunWorkerAsync call. You could hook up a method to the RunWorkerCompleted event and call RunWorkerAsync in there if button3 was pushed.

Upvotes: 0

Deeko
Deeko

Reputation: 1539

Listen for the completed event, and then restart the worker there -

private bool restartOnCancel = false;

private void button3_Click_1(object sender, EventArgs e)
{
    restartOnCancel = true;
    backgroundWorker1.CancelAsync();
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if ((e.Cancelled == true) && restartOnCancel)
    {
        restartOnCancel = false;
        backgroundWorker1.RunWorkerAsync();
    }
}

Upvotes: 3

Related Questions