问题描述
用户到一个TextBox控件。
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.
不过,我似乎并没有能够正确地中断一个已经运行的BackgroundWorker的过程。
However, I don't seem to be able to correctly interrupt an already-running BackgroundWorker process.
我的Visual Basic code:
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
看来,叫我的BackgroundWorker的CancelAsync()后,其IsBusy永远不会成为假。它被卡在一个无限循环。
It seems that after calling my BackgroundWorker's CancelAsync(), its IsBusy never becomes False. It gets stuck in an infinite loop.
我是什么做错了吗?
推荐答案
尝试是这样的:
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();
}
这篇关于我如何正确地取消并重新启动一个BackgroundWorker的进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!