0

我正在编写一个在另一个胎面/后台工作人员上的机器人,我试图阻止它,但在按下取消后,机器人仍在工作 oO

代码在这里://停止我的机器人

        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;
        }
    }
}

//启动我的机器人

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();
    }
}

编辑,跟随评论者链接并在下面得到这个代码它什么都不做,它仍然继续运行

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;
            }
        }
    }
4

1 回答 1

1

您确实意识到您需要CancellationPending在 DoWork() 方法中检查取消(例如通过检查)?CancelAsync() 不会“神奇地停止工作人员”,它只是“发出”您要取消工作人员的“信号”;工人需要中止它正在做的任何事情,清理它的东西等等,然后返回。这个例子可能会为您清除它。

此外,来自CancelAsync 文档

CancelAsync 方法提交停止后台操作的请求并将 CancellationPending 属性设置为 true

当您调用 CancelAsync 时,您的后台操作将能够停止并退出。操作代码应定期检查 CancellationPending 属性以查看它是否已设置为 true。

于 2012-04-05T00:24:19.287 回答