无法停止 BackgroundWorker

Cannot stop the BackgroundWorker

我知道这个问题已经发过好几次了,但是这次的情况不一样。所以假设我正在执行一个需要遍历多个项目(数据库行)的方法,这需要很多时间。
现在在我的 BackgroundWorker 中,我需要在某些情况下停止同步,特别是当用户按下按钮时。我在 _DoWork 事件中所做的是:

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
    while (!worker.CancellationPending)
    {
        LongOperation();
    }
}

现在的问题是当我调用 worker.CancelAsync()LongOperation() 继续执行但不应该! '因为 while 具有 CancellationPending 的条件。我在网上看到这个解决方案是thread-safe,所以我可能做错了什么?

你只需要以下结构

private void runButton_Click(object sender, EventArgs e)
{
    worker=new BackgroundWorker();

    worker.WorkerSupportsCancellation=true;
    worker.RunWorkerCompleted+=Bk_RunWorkerCompleted;
    worker.DoWork+=Bk_DoWork;
    worker.RunWorkerAsync();
}

private void cancelButton_Click(object sender, EventArgs e)
{
    worker.CancelAsync();
}

void ReallyReallyLongOperation(BackgroundWorker worker)
{
    ...within a loop
    if(worker.CancellationPending) 
    {
        return;
    }
}

private void Bk_DoWork(object sender, DoWorkEventArgs e)
{
    ReallyReallyLongOperation(worker);
    if(worker.CancellationPending)
    {
        e.Cancel = true;
    }
}

private void Bk_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if(!e.Cancelled)
    {
        ...
    }
}

the LongOperation() continue the execution but shouldn't! 'cause the while have the condition of CancellationPending.

不,应该继续执行!您对 while 检查的理解完全错误。它不会每秒检查一次取消,它仅在开始 LongOperation!

之前进行检查

所以在这种情况下你唯一能做的就是检查 worker.CancellationPending 属性 inside LongOperation 方法,而不是外部