Demonstra Passo a passo: Multiencadeamento

Esse passo a passo demonstra como criar uma aplicação com multithreading que procura ocorrências de uma palavra num arquivo de texto.Demonstra:

Para criar o exemplo de código para este tópico

  1. Abra um novo projeto de Aplicativo Windows Visual Basic e crie um formulário com o nome Form1.

  2. Adicione dois botões e quatro caixas de texto a Form1.

  3. Nomeie os objetos como mostrado na tabela a seguir.

    Objeto

    Propriedade

    Configuração

    Primeiro botão

    Name, Text

    Iniciar, Iniciar

    Segundo Botão

    Name, Text

    Cancelar, Cancelar

    Primeira caixa de texto

    Name, Text

    Arquivo Fonte, ""

    Segunda caixa de texto

    Name, Text

    ComparaString, ""

    Terceira caixa de texto

    Name, Text

    PalavrasContadas, "0"

    Quarta caixa de texto

    Name, Text

    LinhasContadas, "0"

  4. Adicione um rótulo para cada caixa de texto.Configure a propriedade Text para cada rótulo como mostrado na seguinte tabela.

    Objeto

    Propriedade

    Configuração

    Primeiro rótulo

    Text

    Source File

    Segundo rótulo

    Text

    Comparar String

    Terceiro rótulo

    Text

    Palavras correspondentes

    Quarto rótulo

    Text

    Linhas Contadas

  5. Adicione um componente BackgroundWorker da seção componentes da Caixa de Ferramentas para seu formulário.Isso vai aparecer na bandeja de componentes do formulário.

  6. Configure as seguintes propriedades para o objeto BackgroundWorker1.

    Propriedade

    Configuração

    WorkerReportsProgress

    True

    WorkerSupportsCancellation

    True

Para definir o método que irá rodar num encadeamento diferente

  1. No menu Project, escolha Add Class para adicionar uma classe ao projeto.A caixa de diálogo Add New Item é exibida.

  2. Selecione o modelo CLASS da janela de modelos e digite Words.vb no campo de nome.

  3. Clique em Adicionar.A classe Words é mostrada.

  4. Adicione uma declaração Option Compare ao topo da classe Words, acima da declaração de Class:

    Option Compare Text ' Case insensitive search.
    ' Use Option Compare Binary for case sensitive search.
    
  5. Adicione o seguinte código à classe 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
    

Para manipular eventos do encadeamento

  • Adicione os seguintes manipuladores de eventos ao seu formulário principal:

    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
    

Para iniciar e chamar um novo encadeamento que executa o método WordCount

  1. Adicione o seguinte código ao seu programa:

    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. Chame o método StartThread do botão Start em seu formulário:

    Private Sub Start_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
        Handles Start.Click
    
        StartThread()
    End Sub
    

Para implementar um botão Cancelar que para o encadeamento

  • Chame o procedimento StopThread do manipulador de eventos Click para o botão Cancel.

    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
    

Testando

Agora você pode testar o aplicativo para certificar-se de que ele funciona corretamente.

Para testar o aplicativo

  1. Pressione F5 para executar o aplicativo.

  2. Quando o formulário é mostrado, entre o caminho do arquivo para o arquivo que você deseja testar na caixa sourceFile.Por exemplo, assumindo que seu arquivo de teste é chamado de Test.txt, entre C:\Test.txt.

  3. Na segunda caixa de texto, entre uma palavra ou frase para a aplicação procurar no arquivo texto.

  4. Clique no botão Start.O botão LinesCounted deve começar a incrementar imediatamente.A aplicação mostra a mensagem "Finished Counting" quando acaba.

Para testar o botão Cancelar

  1. Pressione F5 para iniciar a aplicação, e entre o nome do arquivo e procure uma palavra como descrito no procedimento anterior.Certifique que o arquivo que você escolheu é grande o suficiente para garantir que você terá tempo de cancelar o procedimento antes que ele termine.

  2. Clique no botão Start para iniciar a aplicação.

  3. Clique no botão Cancel.A aplicação deve parar de contar imediatamente.

Próximas etapas

Essa aplicação contém alguma manipulação de erros básica.Ela detecta strings de pesquisa em branco.Você pode fazer esse programa mais robusto manipulando outros erros, como exceder o número de palavras ou linhas que podem ser contados.

Consulte também

Tarefas

Demonstra Passo a passo: Criação de um componente Multithreaded Simple com o Visual Basic

Outros recursos

Multithreading no Visual Basic

Date

History

Motivo

Julho de 2008

Erros fixos no WordCount método do exemplo.

Comentários do cliente.