.NET Threading

From HashVB
Revision as of 13:11, 8 May 2008 by Dee (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
float
 This article is based on Visual Basic.NET. Find other Visual Basic.NET articles.
 For information on multithreading in Visual Basic 6, see Multithreading.

Threads in VB.NET are based on the System.Threading namespace. With a thread, you can create a new instance of a class that will appear to run simultaneously with other applications. This is useful for lengthy tasks that would otherwise hang or freeze your application. If you would like to read about threads in VB6, please look at Multithreading.


Creating Your First Thread Application

Create a Class

The first step in creating your thread application is to write your class that will be passed to the thread when it starts. For this example, we will create a simple class that allows for a string to be passed which it will display in a MessageBox.

In our class, we need to have a public method that the thread can access when it starts. This method will be the starting point in our class. For our example, we will use ShowText.

We also need a public event to notify our calling form or class that the class is finished. In this example we will use ThreadClosed. We call this once we are done with the class.

You can copy the following code directly to a new class.vb file.

Your Class (clsHello.vb)

 Public Class clsHello

 #Region " Private Variables "

    'This is the private variable that the class will use to store the message string
    Private str_message As String = ""

 #End Region

 #Region " Public Events "

    'The is the event that will be raised once the thread is finished.
    Public Event ThreadClosed()

 #End Region

 #Region " Public Methods "
    Public Sub ShowText()

        'Show the message assigned to str_message
        MsgBox(str_message)

        'Tell the Thread Handler we are done by calling ThreadClosed
        RaiseEvent ThreadClosed()

    End Sub
 #End Region

 #Region " Public Properties "
    Public Property MessageText() As String
        Get
            Return str_message
        End Get
        Set(ByVal value As String)
            str_message = value
        End Set
    End Property
 #End Region

 End Class


Creating the code to launch the class in a thread

The second step is to create a form. You will need to put a textbox control and a button control on the form. Name the textbox txtMessage and the button btnLaunch. Set the Text property of the button to Launch. (Note: You can name them whatever you want, but for this example, and the following code to work, just name them accordingly.)

To successfully thread out our class above, we need to create a new instance of our class. We also need to reference the System.Threading namespace and create a new instance of a Thread. Once we do these two things we can start to set any parameter values, and to define the method that will be run once the thread starts. In this case, we want the method "ShowText" to be our starting method once thd.Start is called.

To ensure that ShowText is called, we use AddressOf in the definition of the Thread to point to our class.ShowText using the cls variable. (i.e.: thd = New Thread(AddressOf cls.ShowText))

We also need to create a handler for the ThreadClosed event we coded above. This is the code that will be executed after the ThreadClosed event in the class has been raised.

The Code Behind the Form (Form1.vb)

 'Reference Threading Namespace for easier coding
 Imports System.Threading

 Public Class Form1

 #Region " Private Variables "

    'Define the variables for the class and the thread.
    'I do this here so I can properly clean up after the thread is done executing.
    Private cls As clsHello, thd As Thread

 #End Region

 #Region " Private Events "

    'Launch Button Click
    Private Sub btnLaunch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLaunch.Click

        'Create a New Instance of your Class
        cls = New clsHello

        'Assign any properties or other values to the class here.
        cls.MessageText = txtMessage.Text

        'Create a New Thread and give it the AddressOf your method you want to run once the thread starts.
        'In this case, it will be clsHello.ShowText using the reference cls.ShowText
        thd = New Thread(AddressOf cls.ShowText)

        'Add a handler for the event ThreadClosed
        'This will be the code that will be executed once the thread is complete.
        AddHandler cls.ThreadClosed, AddressOf threads_ThreadClosed

        'Start the Thread
        thd.Start()

    End Sub

    'Thread Closed
    Private Sub threads_ThreadClosed()

        If Not thd Is Nothing Then

            'Clean Up
            thd = Nothing
            cls = Nothing

            MsgBox("Your thread has successfully ended.")
        End If
        
    End Sub

 #End Region

 End Class

Finishing Up

Go ahead and run your program. Enter any type of text in the textbox and click the Launch button. You will see that the text is passed to the class and that the thread initiates at the method "ShowText". Once the thread is finished, it raises the ThreadClosed event which executes the code you have in threads_Closed.

Links

For more information on threading in .NET you can check out the following web sites: