| title | Multithreading with the BackgroundWorker Component (Visual Basic) | |
|---|---|---|
| ms.custom | ||
| ms.date | 07/20/2015 | |
| ms.prod | .net | |
| ms.reviewer | ||
| ms.suite | ||
| ms.technology |
|
|
| ms.tgt_pltfrm | ||
| ms.topic | article | |
| ms.assetid | e4cd9b2a-f924-470e-a16e-50274709b40e | |
| caps.latest.revision | 3 | |
| author | dotnet-bot | |
| ms.author | dotnetcontent |
This walkthrough demonstrates how to create a multithreaded Windows Forms application that searches a text file for occurrences of a word. It demonstrates:
-
Defining a class with a method that can be called by the xref:System.ComponentModel.BackgroundWorker component.
-
Handling events raised by the xref:System.ComponentModel.BackgroundWorker component.
-
Starting a xref:System.ComponentModel.BackgroundWorker component to run a method.
-
Implementing a
Cancelbutton that stops the xref:System.ComponentModel.BackgroundWorker component.
-
Open a new Visual Basic Windows Forms Application project, and create a form named
Form1. -
Add two buttons and four text boxes to
Form1. -
Name the objects as shown in the following table.
Object Property Setting First button Name,TextStart, Start Second button Name,TextCancel, Cancel First text box Name,TextSourceFile, "" Second text box Name,TextCompareString, "" Third text box Name,TextWordsCounted, "0" Fourth text box Name,TextLinesCounted, "0" -
Add a label next to each text box. Set the
Textproperty for each label as shown in the following table.Object Property Setting First label TextSource File Second label TextCompare String Third label TextMatching Words Fourth label TextLines Counted
-
Add a xref:System.ComponentModel.BackgroundWorker component from the Components section of the ToolBox to the form. It will appear in the form's component tray.
-
Set the following properties for the BackgroundWorker1 object.
Property Setting WorkerReportsProgressTrue WorkerSupportsCancellationTrue
-
From the Project menu, choose Add Class to add a class to the project. The Add New Item dialog box is displayed.
-
Select Class from the templates window and enter
Words.vbin the name field. -
Click Add. The
Wordsclass is displayed. -
Add the following code to the
Wordsclass: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 line = "" Dim elapsedTime = 20 Dim lastReportDateTime = Now If CompareString Is Nothing OrElse CompareString = System.String.Empty Then Throw New Exception("CompareString not specified.") End If Using myStream As New System.IO.StreamReader(SourceFile) ' Process lines while there are lines remaining in the file. 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 End If ' Uncomment for testing. 'System.Threading.Thread.Sleep(5) End If Loop ' Report the final count values. state.LinesCounted = LinesCounted state.WordsMatched = WordCount worker.ReportProgress(0, state) End Using 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 EscapedCompareString = System.Text.RegularExpressions.Regex.Escape(CompareString) ' To count all occurrences of the string, even within words, remove ' both instances of "\b". Dim regex As New System.Text.RegularExpressions.Regex( "\b" + EscapedCompareString + "\b", System.Text.RegularExpressions.RegexOptions.IgnoreCase) Dim matches As System.Text.RegularExpressions.MatchCollection matches = regex.Matches(SourceString) Return matches.Count End Function End Class
-
Add the following event handlers to your main form:
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 MessageBox.Show("Error: " & e.Error.Message) ElseIf e.Cancelled Then MessageBox.Show("Word counting canceled.") Else MessageBox.Show("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 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
-
Add the following procedures to your program:
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 Words 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
-
Call the
StartThreadmethod from theStartbutton on your form:Private Sub Start_Click() Handles Start.Click StartThread() End Sub
-
Call the
StopThreadprocedure from theClickevent handler for theCancelbutton.Private Sub Cancel_Click() Handles Cancel.Click ' Cancel the asynchronous operation. Me.BackgroundWorker1.CancelAsync() End Sub
You can now test the application to make sure it works correctly.
-
Press F5 to run the application.
-
When the form is displayed, enter the file path for the file you want to test in the
sourceFilebox. For example, assuming your test file is named Test.txt, enter C:\Test.txt. -
In the second text box, enter a word or phrase for the application to search for in the text file.
-
Click the
Startbutton. TheLinesCountedbutton should begin incrementing immediately. The application displays the message "Finished Counting" when it is done.
-
Press F5 to start the application, and enter the file name and search word as described in the previous procedure. Make sure that the file you choose is large enough to ensure you will have time to cancel the procedure before it is finished.
-
Click the
Startbutton to start the application. -
Click the
Cancelbutton. The application should stop counting immediately.
This application contains some basic error handling. It detects blank search strings. You can make this program more robust by handling other errors, such as exceeding the maximum number of words or lines that can be counted.
Threading (Visual Basic)
Walkthrough: Authoring a Simple Multithreaded Component with Visual Basic
How to: Subscribe to and Unsubscribe from Events