如何取消睡眠后台工作人员?

Jac*_*ack 1 c# backgroundworker winforms thread-sleep

我无法取消有其中的后台工作人员Thread.Sleep(100).

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
        int count;
        try
        {
            count = int.Parse(textBox3.Text);

            for (int i = 0; i < count; i++)
            {
                backgroundWorker1.ReportProgress((int)(((double)(i + 1) / count) * 1000));
                //Computation code
                Thread.Sleep(int.Parse(textBox4.Text));
            }
        }
        catch (Exception ex)
        {
            request.DownloadData(url);
            MessageBox.Show(ex.Message);
        }
}

private void cancel_Click(object sender, EventArgs e)
{
    backgroundWorker1.CancelAsync();
    progressBar1.Value = 0;
}
Run Code Online (Sandbox Code Playgroud)

如果我删除Thread.Sleep(100)然后取消工作,但否则它只是继续(进度条不会停止).

编辑:添加了其余的代码

dow*_*for 6

当你调用CancelAsync时,它只是设置一个名为CancellationPendingtrue 的属性.现在你的后台工作者可以而且应该定期检查这个标志是否为真,以便优雅地完成它的操作.因此,您需要将后台任务拆分为可以检查取消的部分.

private void DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        while(true)
        {
            if(worker.CancellationPending)
            {
                e.Cancel = true;
                return;
            }

            Thread.Sleep(100);
        }
    }
Run Code Online (Sandbox Code Playgroud)