2010-04-27 85 views
0

我創建了一個後臺工作人員去執行一個相當長的任務,包括創建更多的線程,這些線程將從一個url文件讀取並抓取每個線程。我試着通過調試來追蹤它,發現後臺進程沒有明顯的原因提前結束。我的代碼的邏輯中是否有錯誤導致此錯誤。我會盡可能地嘗試粘貼以使其合理。後臺工作人員不能正常工作

  While Not myreader.EndOfData 
         Try 
          currentRow = myreader.ReadFields() 
          Dim currentField As String 
          For Each currentField In currentRow 
           itemCount = itemCount + 1 
           searchItem = currentField 
           generateSearchFromFile(currentField) 
           processQuerySearch() 
          Next 
         Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException 
          Console.WriteLine(ex.Message.ToString) 
         End Try 

        End While 

這第一位代碼是從文件輸入的循環,這是後臺工作人員所做的。接下來的代碼是後臺工作者創建線程來處理所有'landingPages'的地方。在創建了大約10個線程後,後臺工作者退出該子文件並跳過文件輸入循環並退出程序。

 Try 
       For Each landingPage As String In landingPages 
        pgbar.Timer1.Stop() 
        If VisitedPages.Contains(landingPage) Then 
         Continue For 
        Else 
         Dim thread = New Thread(AddressOf processQuery) 
         count = count + 1 
         thread.Name = "Worm" & count 
         thread.Start(landingPage) 
         If numThread >= 10 Then 
          For Each thread In ThreadList 
           thread.Join() 
          Next 
          numThread = 0 
          Continue For 
         Else 
          numThread = numThread + 1 
          SyncLock ThreadList 
           ThreadList.Add(thread) 
          End SyncLock 
         End If 
        End If 
        Next 

我,我創建後臺線程主程序如下:

Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click 

    isClicked = True 
    ProgressBar1.Value = 10 
    Me.BackgroundWorker1.RunWorkerAsync() 
    Timer1.Interval = 10000 
    .... 

背景做的不是顯示的功函數,但基本上調用另一類這個功能....

BlogDiscoverObj.start() 

現在我試圖等待所有的線程在這裏在第二塊代碼上面: Dim thread = New Thread(AddressOf processQuery) 計數=計數+ 1 thread.Name = 「蠕蟲」 &計數 thread.Start(的LandingPage) 如果numThread> = 10然後 爲每個線程在對答 的Thread.join() 接着 numThread = 0 繼續對於 否則 numThread = numThread + 1 的SyncLock對答 ThreadList.Add(線程) 完的SyncLock 結束如果 結束如果 接着

  Thread.Sleep(1000) 
      For Each Thread In ThreadList 
       Thread.Join() 
      Next 

希望這是更清晰

而且我的主線程中運行,從那裏這樣的背景下被調用運行,但主線程應該是一個表格,等待後臺進程結束,除非用戶選擇從其他選項主要形式。

回答

2

你的主程序是怎樣的?你正在開始一些後臺線程。後臺線程停止,只要該程序沒有更多的前臺線程存在。

您需要等待退出Main()之前開始完成的線程。