取消BackgroundWorker - Windows窗体(C ++ / CLI)

时间:2012-05-23 15:22:33

标签: .net winforms c++-cli backgroundworker

我在按钮单击事件上触发CancelAsync()方法,以在Windows窗体代码中停止后台工作程序。以下是示例代码

// Windows Form

private: System::Void startButton_Click(System::Object^  sender, System::EventArgs^  e) {
        testBgWorker->RunWorkerAsync();
        }

private: System::Void testBgWorker_DoWork(System::Object^  sender, System::ComponentModel::DoWorkEventArgs^  e) {

            CalculateDistance* calcDistance = new CalculateDistance();
        calcDistance->doCalculations();
         }

private: System::Void stopButton_Click(System::Object^  sender, System::EventArgs^  e) {

            testBgWorker->CancelAsync();
         }

// CalculateDistance.cpp   

void CalculateDistance::doCalculations() {
    for (int i=0; i<1000, i++) 
    {
        // some calculations here
    }
}

如何取消BackgroundWorker(退出for循环)? CancelAsync()似乎无法完成这项工作。

感谢。

1 个答案:

答案 0 :(得分:2)

您需要在CalulateDistance循环中检查取消。在C#中它看起来像这样。 msdn.microsoft.com上的一些很好的例子。你需要将背景工作者标记为支持取消。

 if (worker.CancellationPending)
        {
            e.Cancel = true;
            return "cancelled";
        }