1

我无法取消其中包含 a 的后台工作人员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;
}

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

编辑:添加了其余的代码

4

2 回答 2

6

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

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

            Thread.Sleep(100);
        }
    }
于 2011-10-14T10:25:01.383 回答
0

当您想取消后台线程时,使用 Thread.Interrupt 退出 WaitSleepJoin 状态。

http://msdn.microsoft.com/en-us/library/system.threading.thread.interrupt.aspx

于 2011-10-14T10:24:18.967 回答