Reputation: 73
I am triggering CancelAsync()
method on a button click event to stop a Background Worker in my Windows Form code. The following is the sample code,
// 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
}
}
How can I cancel the BackgroundWorker (exit from for
loop)? CancelAsync()
doesn't seem to do the job.
Thanks.
Upvotes: 0
Views: 1006
Reputation: 45096
You need to check for cancel in the CalulateDistance loop. In C# it looks like this. Some good examples on msdn.microsoft.com. And you need to mark the backgoundworker as support cancelling.
if (worker.CancellationPending)
{
e.Cancel = true;
return "cancelled";
}
Upvotes: 2