2012-04-05 90 views
0

我编码一个机器人那是上另一胎/后台工作,我想阻止它,但按取消BOT后仍然工作OO无法停止后台工作

代码是在这里: //阻止我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; 
     } 
    } 
} 

//开始我的机器人

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

回答

1

你一定要明白,你需要检查取消(通过检查CancellationPending例如)在的DoWork()方法? CancelAsync()不会“神奇地阻止工作人员”,它只是“发出”你想取消工作人员的信号;工作人员需要放弃正在做的事情,清理它的东西等,然后返回。 This example可能会为您清除它。

此外,从CancelAsync documentation

的CancelAsync方法提交请求停止背景 操作和设置CancellationPending属性设置为true

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

+0

检查更新,我不知道该怎么办..它仍然失败。 – TomSwoobs 2012-04-05 00:56:34

+0

现在,您只需复制/粘贴,而不必对自己在做什么有全面的线索。 **示例**的意图是它演示**一些**类的用法。不要只是复制/粘贴它。更完整的解释可以在这里找到(http://msdn.microsoft.com/en-us/library/cc221403(v = vs.95).aspx),[here](http://www.dreamincode .net/forums/topic/112547-using-the-backgroundworker-in-c%23 /)和[here](http://riii.nl/7vnhb)。 – RobIII 2012-04-05 01:02:39

+0

另**提示**:“**工作循环**”在哪里?你认为'(int i = 1;(i <= 1); i ++)'有什么作用?为什么它首先存在(让我回答:盲目地复制/粘贴,是不是?:P)。为什么还要使用背景**工作者**呢?你调用一次Attach()方法一次并设置一个事件处理器;背景工作者在这里有什么用处? – RobIII 2012-04-05 01:08:32