0

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()似乎没有做这项工作。

谢谢。

4

1 回答 1

2

您需要在 CalulateDistance 循环中检查取消。在 C# 中,它看起来像这样。msdn.microsoft.com 上有一些很好的例子。并且您需要将 backgoundworker 标记为支持取消。

 if (worker.CancellationPending)
        {
            e.Cancel = true;
            return "cancelled";
        }
于 2012-05-23T18:43:21.930 回答