逐步解說:多執行緒處理
更新: 2008 年 7 月
本逐步解說示範如何建立多執行緒應用程式 (Multithreaded Application),以搜尋文字檔中的相符文字。其中將示範:
使用可由 BackgroundWorker 元件呼叫的方法定義類別。
處理由 BackgroundWorker 元件引發的事件。
啟動 BackgroundWorker 元件以執行方法。
實作會停止 BackgroundWorker 元件的 [Cancel] 按鈕。
若要建立此主題的程式碼範例
開啟新的 Visual Basic Windows 應用程式專案,並建立名為 Form1 的表單。
將兩個按鈕和四個文字方塊加入 Form1。
如下表所示,為物件命名。
物件
屬性
設定
第一個按鈕
Name, Text
Start、Start
第二個按鈕
Name, Text
Cancel、Cancel
第一個文字方塊
Name, Text
SourceFile、""
第二個文字方塊
Name, Text
CompareString、""
第三個文字方塊
Name, Text
WordsCounted、"0"
第四個文字方塊
Name, Text
LinesCounted、"0"
在每一個文字方塊旁各加上一個標籤。設定每一個標籤的 Text 屬性,如下表所示。
物件
屬性
設定
第一個標籤
Text
Source File
第二個標籤
Text
Compare String
第三個標籤
Text
Matching Words
第四個標籤
Text
Lines Counted
從 [工具箱] 的 [元件] 區段將 BackgroundWorker 元件加入至表單中。這個元件將會出現在表單的元件匣裡。
設定 BackgroundWorker1 物件的下列屬性。
屬性
設定
WorkerReportsProgress
True
WorkerSupportsCancellation
True
若要定義在個別執行緒上執行的方法
從 [專案] 功能表,選擇 [加入類別] 來將類別加入專案中。接著會顯示 [加入新項目] 對話方塊。
在範本視窗中選擇 [類別],並在名稱欄位中輸入 Words.vb。
按一下 [加入],即顯示 Words 類別。
將 Option Compare 陳述式加入至 Words 類別的頂端,位於 Class 陳述式的上方:
Option Compare Text ' Case insensitive search. ' Use Option Compare Binary for case sensitive search.
將下列程式碼加入 Words 類別:
Public Class Words ' Object to store the current state, for passing to the caller. Public Class CurrentState Public LinesCounted As Integer Public WordsMatched As Integer End Class Public SourceFile As String Public CompareString As String Private WordCount As Integer = 0 Private LinesCounted As Integer = 0 Public Sub CountWords( _ ByVal worker As System.ComponentModel.BackgroundWorker, _ ByVal e As System.ComponentModel.DoWorkEventArgs _ ) ' Initialize the variables. Dim state As New CurrentState Dim myStream As System.IO.StreamReader = Nothing Dim line = "" Dim elapsedTime = 20 Dim lastReportDateTime = Now If CompareString Is Nothing Or _ CompareString = System.String.Empty Then Throw New Exception("CompareString not specified.") End If Try ' Open a new stream. myStream = My.Computer.FileSystem.OpenTextFileReader(SourceFile) ' Do while there are lines remaining in the file to be read. Do While Not myStream.EndOfStream If worker.CancellationPending Then e.Cancel = True Exit Do Else line = myStream.ReadLine WordCount += CountInString(line, CompareString) LinesCounted += 1 ' Raise an event so the form can monitor progress. If Now > lastReportDateTime.AddMilliseconds(elapsedTime) Then state.LinesCounted = LinesCounted state.WordsMatched = WordCount worker.ReportProgress(0, state) lastReportDateTime = Now.AddMilliseconds(elapsedTime) End If End If Loop ' Report the final count values. state.LinesCounted = LinesCounted state.WordsMatched = WordCount worker.ReportProgress(0, state) Finally If myStream IsNot Nothing Then ' Close the file. myStream.Close() End If End Try End Sub Private Function CountInString( _ ByVal SourceString As String, _ ByVal CompareString As String _ ) As Integer ' This function counts the number of times ' a word is found in a line. If SourceString Is Nothing Then Return 0 End If Dim regex As New System.Text.RegularExpressions.Regex( _ System.Text.RegularExpressions.Regex.Escape(CompareString)) Dim matches As System.Text.RegularExpressions.MatchCollection matches = regex.Matches(SourceString) Return matches.Count End Function End Class
若要處理執行緒中的事件
將下列事件處理常式加入您的主表單:
Private Sub BackgroundWorker1_RunWorkerCompleted( _ ByVal sender As Object, _ ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _ Handles BackgroundWorker1.RunWorkerCompleted ' This event handler is called when the background thread finishes. ' This method runs on the main thread. If e.Error IsNot Nothing Then MsgBox("Error: " & e.Error.Message) ElseIf e.Cancelled Then MsgBox("Word counting canceled.") Else MsgBox("Finished counting words.") End If End Sub Private Sub BackgroundWorker1_ProgressChanged( _ ByVal sender As Object, _ ByVal e As System.ComponentModel.ProgressChangedEventArgs) _ Handles BackgroundWorker1.ProgressChanged ' This event handler is called after the background thread ' reads a line from the source file. ' This method runs on the main thread. Dim state As Words.CurrentState = _ CType(e.UserState, Words.CurrentState) Me.LinesCounted.Text = state.LinesCounted.ToString Me.WordsCounted.Text = state.WordsMatched.ToString End Sub
若要啟動和呼叫執行 WordCount 方法的新執行緒
將下列程序加入至您的程式中:
Private Sub BackgroundWorker1_DoWork( _ ByVal sender As Object, _ ByVal e As System.ComponentModel.DoWorkEventArgs) _ Handles BackgroundWorker1.DoWork ' This event handler is where the actual work is done. ' This method runs on the background thread. ' Get the BackgroundWorker object that raised this event. Dim worker As System.ComponentModel.BackgroundWorker worker = CType(sender, System.ComponentModel.BackgroundWorker) ' Get the Works object and call the main method. Dim WC As Words = CType(e.Argument, Words) WC.CountWords(worker, e) End Sub Sub StartThread() ' This method runs on the main thread. Me.WordsCounted.Text = "0" ' Initialize the object that the background worker calls. Dim WC As New Words WC.CompareString = Me.CompareString.Text WC.SourceFile = Me.SourceFile.Text ' Start the asynchronous operation. BackgroundWorker1.RunWorkerAsync(WC) End Sub
從您表單上的 [Start] 按鈕呼叫 StartThread 方法:
Private Sub Start_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Start.Click StartThread() End Sub
若要實作停止執行緒的 Cancel 按鈕
從 [Cancel] 按鈕的 Click 事件處理常式呼叫 StopThread 程序。
Private Sub Cancel_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Cancel.Click ' Cancel the asynchronous operation. Me.BackgroundWorker1.CancelAsync() End Sub
測試
現在您可以測試應用程式,以確定程式運作正確。
若要測試應用程式
請按 F5 執行應用程式。
顯示表單時,請在 [sourceFile] 方塊中,輸入您想要測試檔案的檔案路徑。例如,假設您測試檔的名稱為 Test.txt,請輸入 C:\Test.txt。
在第二個文字方塊中,輸入要在文字檔中搜尋的應用程式的文字或片語。
按一下 [Start] 按鈕。[LinesCounted] 按鈕應該會立刻開始遞增。動作結束時,應用程式會出現「完成計數」訊息。
若要測試 Cancel 按鈕
按 F5 啟動應用程式,並依照之前的程序,輸入檔案名稱和搜尋文字。請確定您選擇的檔案夠大,以確保檔案結束之前,會有時間能夠取消這個程序。
按一下 [Start] 按鈕,啟動應用程式。
按一下 [Cancel] 按鈕。應用程式應該會立刻停止計數。
後續步驟
本應用程式包含某些基本的錯誤處理。它會偵測空白的搜尋字串。藉由處理其他錯誤,例如超過可計數的最大字數或行數,可讓此程式更為強固。
請參閱
工作
逐步解說:使用 Visual Basic 撰寫簡單的多執行緒元件
其他資源
變更記錄
日期 |
記錄 |
原因 |
---|---|---|
2008 年 7 月 |
修正範例中 WordCount 方法的錯誤。 |
客戶回函。 |