I am coding a bot that's on another tread / background worker and I am trying to stop it, but after pressing cancel the bot is still working o.O
Code is here: //Stop my bot
private void botOff_Click(object sender, EventArgs e)
{
bot_worker.WorkerSupportsCancellation = true;
if (bot_worker.IsBusy)
bot_worker.CancelAsync();
botOn.Text = "Enable";
botOn.Enabled = true;
botOff.Enabled = false;
}
}
}
//start my bot
private void botOn_Click(object sender, EventArgs e)
{
if (toolStripLabel5.Text == "Not attached")
{
MessageBox.Show(notAttached, "Skype Pwnage - Info!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
botOn.Text = "Running";
botOn.Enabled = false;
botOff.Enabled = true;
bot_worker.RunWorkerAsync();
}
}
Edit, followed a commenters link and got this code below it does nothing at all, it still continues to run
private void bot_worker_DoWork(object sender, DoWorkEventArgs e)
{
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; (i <= 1); i++)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
skype.Attach(7, false);
skype.MessageStatus += new _ISkypeEvents_MessageStatusEventHandler(skype_MessageStatus);
}
}
}
}
private void skype_MessageStatus(ChatMessage msg, TChatMessageStatus status)
{
try
{
string command = msg.Body.Remove(0, trigger.Length).ToLower();
string[] lines = richTextBox4.Text.Split('\n');
foreach (string ln in lines)
{
string[] commands = ln.Split(':');
if (command == commands[0])
{
listBox2.Items.Add(commands[0]);
skype.SendMessage(msg.Sender.Handle, string.Format(commands[1]));
break;
}
}
}
You do realise that you need to check the cancellation (by checking CancellationPending
for example) in the DoWork() method? The CancelAsync() does not "magically stop the worker", it merely 'signals' that you want to cancel the worker; the worker needs to abort whatever it's doing, clean up it's stuff etc. and then return. This example might clear it up for you.
Also, from the CancelAsync documentation:
The CancelAsync method submits a request to stop the background operation and sets the CancellationPending property to true.
When you call CancelAsync, your background operation will be able to stop and exit. The operation code should periodically check the CancellationPending property to see whether it has been set to true.
for (int i = 1; (i <= 1); i++)
does? Why is it there in the first place (let me answer that: copy/pasted it blindly, didn't you? :P ). And why use a backgroundworker for this anyway? You call some Attach() method once and set up an eventhandler; what's the use of the backgroundworker here - RobIII 2012-04-05 01:08