演练:多线程处理

更新:2007 年 11 月

该演练说明如何创建一个多线程应用程序,该程序在文本文件中搜索字词的匹配项。它演示:

生成此主题的代码示例

  1. 打开新的 Visual Basic Windows 应用程序项目,并创建一个名为 Form1 的窗体。

  2. 向 Form1 中添加两个按钮和四个文本框。

  3. 如下表所示命名对象。

    对象

    属性

    设置

    第一个按钮

    Name, Text

    Start, Start

    第二个按钮

    Name, Text

    Cancel, Cancel

    第一个文本框

    Name, Text

    SourceFile, ""

    第二个文本框

    Name, Text

    CompareString, ""

    第三个文本框

    Name, Text

    WordsCounted, "0"

    第四个文本框

    Name, Text

    LinesCounted, "0"

  4. 近邻每个文本框添加一个标签。为每个标签设置 Text 属性,如下表所示。

    对象

    属性

    设置

    第一个标签

    Text

    Source File

    第二个标签

    Text

    Compare String

    第三个标签

    Text

    Matching Words

    第四个标签

    Text

    Lines Counted

  5. 将“工具箱”的“组件”部分中的 BackgroundWorker 组件添加到窗体。它将出现在窗体的组件栏中。

  6. 为 BackgroundWorker1 对象设置下列属性。

    属性

    设置

    WorkerReportsProgress

    True

    WorkerSupportsCancellation

    True

定义将在单独的线程上运行的方法

  1. 从“项目”菜单中选择“添加类”,在项目中添加类。显示“添加新项”对话框。

  2. 从模板窗口选择“类”,并在名称字段内输入 Words.vb。

  3. 单击“添加”。显示 Words 类。

  4. 将 Option Compare 语句添加到 Words 类的顶部(Class 语句的上方):

    Option Compare Text ' Case insensitive search.
    ' Use Option Compare Binary for case sensitive search.
    
  5. 将下面的代码添加到 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 方法的新线程

  1. 将下面的过程添加到程序中:

    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
    
  2. 通过窗体上的 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
    

测试

现在可以测试该应用程序以确保其正确运行。

测试应用程序

  1. 按 F5 运行该应用程序。

  2. 显示窗体时,在 sourceFile 框中输入要测试的文件的路径。例如,假定测试文件名为 Test.txt,则输入 C:\Test.txt。

  3. 在第二个文本框中,输入要让该应用程序在文本文件中搜索的字词或短语。

  4. 单击 Start 按钮。LinesCounted 按钮应当立即开始递增。在任务完成后,应用程序将显示“计数完成”(Finished Counting) 消息。

测试 Cancel 按钮

  1. 按 F5 以启动该应用程序,按照前面过程中所述内容输入文件名和搜索字词。确保所选择的文件足够大,以确保在搜索结束之前有时间取消该过程。

  2. 单击Start按钮启动该应用程序。

  3. 单击 Cancel 按钮。应用程序应该立即停止计数。

后续步骤

此应用程序包含一些基本错误处理。它检测空白搜索字符串。可以通过处理其他错误(如超过可以计数的最大字词数或行数)使该程序更加可靠。

请参见

任务

演练:用 Visual Basic 创作简单的多线程组件

其他资源

多线程处理 (Visual Basic)

修订记录

日期

修订

原因

2008 年 7 月

修复了示例中 WordCount 方法的错误。

客户反馈。