Browse DevX
Sign up for e-mail newsletters from DevX


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

Launching new threads is easy, but it's not as obvious how you can pass parameters to the threads and get the results back. In addition, accessing Windows Forms controls from multiple threads can cause problems. In this article, you'll see how to pass parameters, receive results, and access controls safely from multiple threads in a Windows Forms application.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.


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.

Thanks for your registration, follow us on our social networks to keep up-to-date