.net – How to properly cancel and restart a BackgroundWorker process

backgroundworkermultithreadingnet

Users of my application type HTML into a TextBox control.

I want my application to validate their input in the background.

Because I don't want to hammer the validation service, I've tried to build in a one-second delay before each validation.

However, I don't seem to be able to correctly interrupt an already-running BackgroundWorker process.

My Visual Basic code:

Sub W3CValidate(ByVal WholeDocumentText As String)

    'stop any already-running validation
    If ValidationWorker.IsBusy Then
        ValidationWorker.CancelAsync()
        'wait for it to become ready
        While ValidationWorker.IsBusy
            'pause for one-hundredth of a second
            System.Threading.Thread.Sleep(New TimeSpan(0, 0, 0, 0, 10))
        End While
    End If

    'start validation
    Dim ValidationArgument As W3CValidator = New W3CValidator(WholeDocumentText)
    ValidationWorker.RunWorkerAsync(ValidationArgument)

End Sub

It seems that after calling my BackgroundWorker's CancelAsync(), its IsBusy never becomes False. It gets stuck in an infinite loop.

What am I doing wrong?

Best Answer

Try something like this:

bool restartWorker = false;

    void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
                    // add other code here
        if (e.Cancelled && restartWorker)
        {
            restartWorker = false;
            backgroundWorker1.RunWorkerAsync();
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (backgroundWorker1.IsBusy)
        {
            restartWorker = true;
            backgroundWorker1.CancelAsync();
        }
        else
            backgroundWorker1.RunWorkerAsync();
    }