How To Pass Parameters to Threads in Windows Forms Applications—and Get Results

he .NET framework makes it easy to start code execution on a new thread?improving user interface design by letting you execute lengthy procedures on one thread while leaving the UI thread active and available to handle user interaction.

Starting a new thread is simple in VB.NET?you add the System.Threading namespace to your module to simplify naming, create a new thread using a delegate to tell it which method to start in, and then call its Start method to begin execution.

For example, suppose you have a button on a form; when the user presses the button, you want to launch a separate thread that performs some task. For this article, a simple counter method suffices to simulate a long-running procedure.

Note: The downloadable code for this article contains both VB.NET and C# versions.

   Sub Count()      Dim i As Integer         ' loop 25 times      For i = 1 To 25         ' show the counter value         Console.WriteLine(i.ToString)                  ' sleep 100 milliseconds         Thread.CurrentThread.Sleep(100)      Next   End Sub


But rather than showing the user an hourglass cursor and disabling the button while the task executes, you want to let the user continue to interact with the program. Create a new Windows Form with a button named btnLaunchThread and set its Text property to Launch Thread. Next, create a Count() method that counts from 1 to 25, writing the current counter value to the Output window. Because that would normally happen very quickly, the code also uses the Thread.CurrentThread method to get the currently executing thread, and causes it to sleep for 100 milliseconds, which simulates a lengthy process better. Here’s the code.

   ' At the top of the form   Imports System.Threading      ' Inside the class       Private Sub btnLaunchThread_Click( _      ByVal sender As System.Object,       ByVal e As System.EventArgs)       Handles btnLaunchThread.Click         ' create the thread using a Count delegate      Dim t As Thread = New Thread(AddressOf Count)         ' start the thread      t.Start()   End Sub


Run the code and click the Launch Thread button. You’ll see the output window slowly fill with numbers from 1 to 25. Click the button again?in fact, click it several times. What happens? Each time you click the button, the application launches a new thread, which then starts displaying numbers in the output window. To make things a little clearer, you can assign each thread a name and display that as well. The sample Form1.vb file contains the altered code:

   Option Strict On   Imports System.Threading   Public Class Form1      Inherits System.Windows.Forms.Form      Dim threadCount As Integer      ' omitted -- Windows Form Designer generated code "      Private Sub btnLaunchThread_Click( _      ByVal sender As System.Object, _      ByVal e As System.EventArgs) _      Handles btnLaunchThread.Click      Dim t As Thread = New Thread(AddressOf Count)      threadCount += 1      t.Name = "Thread " & threadCount.ToString      t.Start()   End Sub      Sub Count()      Dim i As Integer      For i = 1 To 25         Console.WriteLine(Thread.CurrentThread.Name & _            ": " & i.ToString)         Thread.CurrentThread.Sleep(100)      Next   End Sub      End Class


After changing the code, when you click the button several times, you’ll see each thread’s name appear in front of the counter value. That’s straightforward enough. Each button click launches an individual thread that counts from 1 to 25. But what if you didn’t know how many times to loop? What if you wanted the user to specify a value for the number of counter iterations, and pass that to the new thread?

Here’s where the simplicity breaks down a little. The Thread class constructor accepts only a ThreadStart delegate (the delegate that represents the method in which to start the thread), and there’s no overloaded Thread.Start() method that accepts parameter values.

Pass Parameters to Threads with a Class
The trick is to start the thread in the context of a class that already has the parameter values you want to send. Rather than launching the new thread directly from the btnLaunchThread_Click event, you create a new class that has properties to hold the ThreadStart delegate and the number of counter iterations.

Figure 1: This process flow diagram shows the sequence to launch a thread using a separate class to pass parameters. The main form thread (which runs the UI) is essentially unaffected by the new thread.

The CounterArgs class serves that purpose. The public iterations field holds the number of counter iterations, and the startDelegate field holds a StartCounterDelegate, which is a pre-created delegate that matches the Count() method in the form. The class has one method, StartCounting(), which calls the method represented by the StartCounterDelegate (the Count() method) and passes the number of iterations. In other words, to launch a new thread and pass the number of iterations, you create a new CounterArgs class, set its Iterations property, and then create a new StartCounterDelegate which represents the Count() method. Finally, you create a new Thread with a ThreadStart delegate that represents the CounterArgs.StartCounting method. When you start the new thread, it runs in the CounterArgs class, and therefore it has access to the values of the Iterations and StartDelegate fields. Figure 1 shows the process.

Here’s the complete code for the CounterArgs class.

   Private Class CounterArgs      Public Iterations As Integer      Public StartDelegate As StartCounterDelegate         Public Sub StartCounting()         StartDelegate(Iterations)      End Sub   End Class

The remaining code is simple: create a Count method that accepts the number of iterations to count.

      Public Sub Count(ByVal iterations As Integer)      Dim i As Integer      For i = 0 To iterations         Console.WriteLine(Thread.CurrentThread.Name & _            ": " & i.ToString)      Next   End Sub

When you click the button on Form 1, the thread starts and writes the expected output?and if you click the button several times, you’ll see the correct output for each thread.

   Private Sub btnLaunchThread_Click( _      ByVal sender As System.Object, _      ByVal e As System.EventArgs) _      Handles btnLaunchThread.Click         Dim iterations As Integer      Try         iterations = CInt(Me.txtIterations.Text)      Catch ex As System.InvalidCastException         Beep()         Exit Sub      End Try            Dim ca As New CounterArgs()      ca.Iterations = iterations      ca.StartDelegate = AddressOf Count      Dim t As New Thread(AddressOf ca.StartCounting)      threadCount += 1      t.Name = "Thread " & threadCount.ToString()      Console.WriteLine("starting thread " & _        t.Name & " to count " & iterations & _        " times.")      t.IsBackground = True      t.Start()   End Sub

Accessing Windows Controls from Launched Threads
You might ask: Why not just have the Count() method grab the iteration parameter value from the txtIterations control? That’s a good question. The answer is that Windows Forms are not thread-safe?they run on a single thread, and if you try to access the controls on a form from multiple threads, you’re bound to have problems. You should only access Windows Forms controls from the thread on which they were created. In this article, I’ve called that the “main form thread”.

To make matters worse, you can access the controls from other threads without causing an exception?despite the fact that you shouldn’t. For example, if you write code to grab the txtIteration.Text value, it will usually work. More commonly, you want to write to Windows Forms controls from multiple threads, for example, changing the contents of a TextBox?and because that alters the control data, it’s where most control threading problems occur.

The sample Form3.vb file shows you how to access and update control values safely. The form launches the threads in the same way you’ve already seen, but displays the results in a multi-line TextBox. To access Windows controls safely from a different thread, you should query the InvokeRequired property implemented by the Control class and inherited by all the standard controls. The property returns True if the current thread is not the thread on which the control was created?in other words, a return value of True means you should not change the control directly from the executing thread. Instead, call the control’s Invoke() method using a delegate and (optionally) a parameter array of type Object. The control uses the delegate to call the method in the context of its own thread, which solves the multithreading problems. This is the only thread-safe way to update control values.

In Form 3, the button click code is identical to the code in Form 2?it creates a thread and starts it. The Count() method is different; it contains the check for InvokeRequired, and a SetDisplayText() method to handle the control update. The Count() method code looks more complicated than it is.

   Private Sub Count(ByVal iterations As Integer)      Dim i As Integer      Dim t As Thread = Thread.CurrentThread      For i = 0 To iterations         If Me.txtDisplay.InvokeRequired Then            Me.txtDisplay.Invoke( _            New ChangeTextControlDelegate( _            AddressOf SetDisplayText), New Object() _            {t.Name, txtDisplay, i.ToString})         Else            Me.SetDisplayText(t.Name, txtDisplay, _            i.ToString)         End If         If Me.txtDisplay.InvokeRequired Then            t.Sleep(100)         End If      Next      If Me.txtDisplay.InvokeRequired Then         Me.txtDisplay.Invoke( _         New ChangeTextControlDelegate( _         AddressOf SetDisplayText), New Object() _         {t.Name, txtDisplay, "Ending Thread"})      Else         Me.SetDisplayText(t.Name, txtDisplay, _         "Ending Thread")      End If   End Sub

Within the loop, the application checks to see if the current thread is capable of directly altering the txtDisplay TextBox contents, by checking the value of InvokeRequired. When the value returns True the code uses the Control.Invoke method to call the SetDisplayText() method via a ChangeTextControl delegate:

   Delegate Sub ChangeTextControlDelegate( _      ByVal aThreadName As String, _      ByVal aTextBox As TextBox, _      ByVal newText As String)

The SetDisplayText() method appends the name of the thread and the newText parameter to the specified TextBox. Because TextBoxes have a maximum length, the SetDisplayText() method checks to ensure that the TextBox is not “full” of text; if it is, it removes all but the last 1,000 characters before appending the new text. If the TextBox is not full, the code simply appends the new text.

   Public Sub SetDisplayText( _      ByVal aThreadName As String,       ByVal aTextBox As TextBox,       ByVal newText As String)      If aTextBox.Text.Length + newText.Length > _         aTextBox.MaxLength Then         aTextBox.Text = Strings.Right( _            aTextBox.Text, 1000)      End If      aTextBox.AppendText(aThreadName & ": " & _         newText & System.Environment.NewLine)   End Sub

Why Not Always Use Control.Invoke?
Strictly speaking, you don’t need to check the InvokeRequired property for this particular application, because here only new threads call the Count() method, so InvokeRequired always returns True, and the Else portion of the two If structures never fires. In fact, if you’re willing to take a miniscule performance hit, you can simply eliminate the check and always use the Invoke method. Calling Invoke from the main form thread doesn’t raise an exception. You should try it yourself, to see what happens.

Here’s a simplified version of Count that always uses Invoke.

   Public Sub Count(ByVal iterations As Integer)      Dim i As Integer      For i = 0 To iterations         Me.txtDisplay.Invoke(New ChangeTextControl( _            AddressOf SetDisplayText), New Object() _           {Thread.CurrentThread.Name, txtDisplay, _           i.ToString})         Thread.CurrentThread.Sleep(100)      Next      Me.txtDisplay.Invoke(New ChangeTextControl( _         AddressOf SetDisplayText), New Object() _         {Thread.CurrentThread.Name, txtDisplay, _         "Ending Thread " & Thread.CurrentThread.Name})   End Sub

To test it, add this line to the end of the btnStartThread_Click event code to call the Count() method on the main form thread.

   Me.Count(i)

Unfortunately, you’ll find that this simpler version does freeze the interface until the main form thread loop finishes, which is exactly why you want to use a separate thread to begin with. If you leave the call to Count() in place at the end of the btnStartThread_Click event but run it against the previous version of the Count() method instead, the interface is “live,” but the button won’t depress while the main form thread counter is running (because the thread is “asleep” most of the time inside the loop). Interestingly though, the button does still accumulate clicks?the form sticks the click events in the message queue until the current main-thread loop exits. If you continue to click the button the application dutifully launches a new thread for each click?even though you won’t see the button depress.

Returning Values from Launched Threads
You’ve seen how to pass parameters to a launched thread; but what if you want to return the results?for example, suppose the thread calculates a total value and you need to know that value in the main thread? To do that you’ll need to know when the thread exits and you’ll need to be able to access the total value.

The sample Form4.vb contains the code to retrieve the total value. First, alter the Count() method so it creates a total value and returns the total when the loop completes. You need to alter the StartCountingDelegate to match the new signature as well. The boldface lines in the following code show the changes.

   Delegate Function StartCounterDelegate( _      ByVal iterations As Integer) As Integer   Public Function Count(ByVal iterations As Integer) _      As Integer      Dim i As Integer      Dim t As Thread = Thread.CurrentThread      Dim total As Integer      For i = 0 To iterations         total += i         If Me.txtDisplay.InvokeRequired Then            Me.txtDisplay.Invoke( _            New ChangeTextControlDelegate( _            AddressOf SetDisplayText), New Object() _            {t.Name, txtDisplay, i.ToString})         Else            Me.SetDisplayText(t.Name, _               txtDisplay, i.ToString)         End If         If Me.txtDisplay.InvokeRequired Then            t.Sleep(100)         End If      Next      If Me.txtDisplay.InvokeRequired Then         Me.txtDisplay.Invoke( _         New ChangeTextControlDelegate( _         AddressOf SetDisplayText), New Object() _         {t.Name, txtDisplay, "Ending Thread"})      Else         Me.SetDisplayText(t.Name, txtDisplay, _         "Ending Thread")      End If      Return total   End Function

The thread launches in the context of the CounterArgs class, so you can get the return value there, but more typically, you’d want the CounterArgs class to notify the main form thread when the count is done and the results are available. The answer is to create an event and raise it in the CounterArgs class when the Count() method returns. The DoneCounting event passes the current thread name and the total to the event handler. Although you can pass anything you want as event arguments, the .NET convention is to pass the object invoking the event as the first argument and pass an EventArgs, or a class derived from EventArgs as the second argument. The DoneCountingEventArgs class inherits from EventArgs and contains the data you need to send.

   Private Class DoneCountingEventArgs      Inherits EventArgs      Private m_threadName As String      Private m_total As Integer      Public Sub New(ByVal threadName As String, ByVal total As Integer)         m_threadName = threadName         m_total = total      End Sub      Public ReadOnly Property ThreadName() As String         Get            Return m_threadName         End Get      End Property      Public ReadOnly Property Total() As Integer         Get            Return m_total         End Get      End Property   End Class

Here are the alterations you need to make to the CounterArgs class.

   Private Class CounterArgs         Public Event DoneCounting( _         ByVal sender As Object, _         ByVal e As DoneCountingEventArgs)      Public iterations As Integer      Public startDelegate As StartCounterDelegate      Public Sub StartCounting()         Dim total As Integer         total = startDelegate(iterations)         Dim args As New DoneCountingEventArgs(Thread.CurrentThread.Name, total)         RaiseEvent DoneCounting(Me, args)      End Sub   End Class

Next you need an event-handler in the main form to handle the DoneCounting event and display the total:

   Private Sub Done(ByVal object As Sender, _      ByVal e As DoneCountingEventArgs)      Console.WriteLine(e.ThreadName & ": Total=" & _         e.Total.ToString)   End Sub

Then, wire the event to the new handler in the btnLaunchThread_Click code:

      AddHandler ca.DoneCounting, AddressOf Done

That’s it. When you run Form 4, you’ll see the thread name and total appear in the Output window.

One final note: The Done() method is defined in the main form, but the CounterArgs class raises the DoneCounting event from the launched thread. When that event fires, it causes the Done() method to execute. Which thread do you think the Done() method executes on, the main form thread, or the launched thread? Add this code to the Done() method to find out.

   If txtDisplay.InvokeRequired Then      Console.Write("Done is executing on the " & _         "launched thread.")   Else      Console.Write("Done is executing on the " & _         "main form thread.")   End If

When you add the preceding code and run Form 4, you’ll see that the event-handler runs in the context of the thread that raised the event. Therefore, you have to be careful how you access controls in event-handlers that might be fired by launched threads

Another way to perform the same task is to create an EndCounterDelegate with the same signature as the Done() method. Add a public field of type EndCounterDelegate to the CounterArgs class, set the delegate’s method to the Done() method, and call it when the Count() method completes. As both the concept and the code is nearly identical to the event-raising example in Form 4, I won’t show it here, but you can find it in the downloadable sample code in Form 5. Note that you must check IsInvokeRequired using this technique as well.

To sum up, to pass parameters to threads, you need to launch them in the context of a class that has access to the parameter values. To return values created during the execution of a launched thread, raise events or use a delegate to pass the values to a specific method when the thread exits. If you need to access controls created on the main form thread during thread execution, always use the InvokeRequired property to check whether you need to use the control’s Invoke() method to access its data.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS