I want to stop BackgroundWorker when click stop button, the Background Worker execute callback function to show message.
I'm trying stop in BackgroundWorker DoWork(), but doesn't work, how should do it?
WorkerSupportsCancellation is true.
private void ShowDebug(string msg)
{
this.Invoke(new Action( () => { txtBoxDebug.AppendText(msg); }));
this.Invoke(new Action( () => { txtBoxDebug.AppendText(Environment.NewLine); }));
}
private void BtnTest(object sender, EventArgs e)
{
if (cbBoxAdapterList.SelectedIndex == -1)
{
ShowDebug("Select an adapter");
return;
}
selectDevice = allDevices[cbBoxAdapterList.SelectedIndex];
bkgrdTest.RunWorkerAsync();
}
private void BkgrdTestDoWork(object sender, DoWorkEventArgs e)
{
using (PacketCommunicator communicator = selectDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
{
ShowDebug("Begin Capture");
communicator.ReceivePackets(0, PacketHandlerTest);
if (bkgrdTest.CancellationPending == true)
{
e.Cancel = true;
return;
}
}
}
private void PacketHandlerTest(Packet packet)
{
ShowDebug("Packet length: " + packet.Length.ToString());
Thread.Sleep(500);
}
private void BtnStop(object sender, EventArgs e)
{
if (bkgrdTest.IsBusy)
{
bkgrdTest.CancelAsync();
}
}