2012-04-05 88 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