2014-10-04 69 views
-1

這裏是我的代碼,收藏已修改;枚舉操作可能不會執行。 VB thearding

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 
    For Each kthread As Thread In _threads 
     If kthread.Name = "123" Then 
      _threads.Remove(kthread) 
      kthread.Abort() 
      killedthreads += 1 'a integer 
     End If 
    Next 
End Sub 

我加入了killedthreads整數最後的檢查,VB執行整體功能不錯,但在最後一行總是扔在標題中的錯誤表示。 不知道爲什麼,如果killedthreads + = 1不存在,那麼錯誤將發生在kthread.Abort()

今年早些時候,我在C#中遇到了與其他應用程序相同的問題。

編輯,

Public Sub KillThread(kThread As Thread) 

     For i As Integer = (_threads.Count - 1) To 0 Step -1 
      If _threads.Item(i).Name = kThread.Name Then 
       _threads.Item(i).Abort() 
       _threads.RemoveAt(i) 
      End If 
     Next 

    End Sub 

我沒有這個代碼阿姆說了出來。如果某些東西不好,或者它已經完成了所有的功能,它將從正在運行的線程中獲取k線程。但我的問題是,只有第一個發送它的線程會被中止並從列表中移除,其他線程在第一個線程中止後會被卡住。

我使用創建線程,

Public Sub multiThreader(int As Integer, link As String) 
     Dim tCount As Integer = _threads.Count 
     If tCount >= Form1.ListView1.Items.Count Then 
     Else 
      Dim dy As Integer = DateTime.Now.Day 
      Dim mo As Integer = DateTime.Now.Month 
      Dim fileNum As String = dy.ToString() + "-" + mo.ToString() + "_" + int.ToString 

      botThread = New Thread(Sub() MainThread(fileNum, link, botThread, int.ToString())) 
      botThread.IsBackground = True 
      botThread.Name = String.Format("AutoBotThread{0}", fileNum) 
      _threads.Add(botThread) 
      botThread.Start() 
     End If 
    End Sub 

和_threads是公開,Public _threads As New List(Of Thread)

MainThread是它運行的功能,並得到返回,並在一定條件下發送KillThread一個公用Sub。

+0

[Collection的可能重複被修改;枚舉操作可能不會執行](http://stackoverflow.com/questions/604831/collection-was-modified-enumeration-operation-may-not-execute) – 2014-10-04 08:58:51

+1

使用'For I As Integer =(_threads.Length - 1)改爲0步驟-1'。 – 2014-10-04 09:00:09

+0

但其中有很多不同的線程。 _threads是一個線程列表 – kks21199 2014-10-04 09:49:09

回答

0

問題是,在完成迭代之前,您從枚舉中刪除了一個項目。

這就像從0迭代到list.count,當計數從迭代變爲另一個迭代時。作爲比約恩 - 羅傑Kringsjå說,你應該做這樣的事情:

For i As Integer = (_threads.count - 1) to 0 Step -1 
    If _threads.Item(i).Name = "123" Then 
     _threads.Item(i).Abort 
     _threads.RemoveAt(i) 
     killedthreads += 1 'a integer 
    End If 
Next 

使用Step -1您確保一個索引超出範圍的錯誤不會發生,並確保您的操作,安裝和執行在正確的順序/項目。

+0

但我如何中止線程?我希望它停止運行。它的多線程 – kks21199 2014-10-04 10:04:24

+0

嘿,你能看到我更新的questiojn – kks21199 2014-10-06 11:42:08

相關問題