Threading is not nearly so hard as you may think. And there are many places in even the simplest of programs where multithreading can come in helpful. One common bug that everyone has runinto at some point in time (wether in a .Net app, or a professional app) is that when the application hit's a heavy load, or is running Input/Output code, the display will bog, hang, go white, and you won't be able to interact with it.
This happens because the Primary thread of any application is repsoncible for painting and interaction. When ever you add instence code to this thread (by not multithreading) you will create a situation where the GUI will bog.
On common fix that people use is the
DoEvents command. DoEvents is handy, but it's pretty much just a crutch for making the primary thread do it's painting/interaction. DoEvents will slow down your code, expecially in a loop where it will be called every iteration. DoEvents is also limited, if you have one intense command (like a dataadapter.fill) putting DoEvents on either side of the command won't help while the command is running.
A solution exists:
Threading. Threading, as handy as it is now will in the future become even more important as Intell/AMD/Sun/Via/IBM and others start pushing multi-core processors that can take full advantage of multiple threads.
The following is a quick form I through together for this sample:[img http://ringdev.com/code/ThreadingSampleForm.JPG] Nothing fancy, just a status bar, a label and a button (all default names and properties)
In the code, at the top of the class, put in:
Then add two subs, one for the Button Click Event:
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim tCounter As New Thread(AddressOf RunCounter)
tCounter.Start()
End Sub
And one for the Counter:
Code:
Private Sub RunCounter()
Dim Counter As Integer
Me.ProgressBar1.Maximum = 100000
Do
Me.Label1.Text = Counter & "/" & 100000
Me.ProgressBar1.Value = Counter
Counter += 1
Loop While Counter < 100000
End Sub
The RunCounter method is pretty straight forward, it loops 100,000 times while updating a progress bar and label.
The call to it is the important part. First we define a new
Thread. When we create the thread we give it a method name, that is the starting point of the thread. The thread will continue executing until that method is complete. Then we tell it to start. This is kind of a 'Fire and Forget' method of threading. Once it starts, the Thread object goes out of scope (but the thread continues). We don't have any easy ways of interacting with this thread (A topic for another FAQ). But it's still extremely usefull for running processes outside of the primary thread.
I'll try to update this FAQ and put some more together in the future, but you may want to google the following topics for more information: Delegates, Thread Interaction, Locking and Thread Saftey, InvokeRequired, and BeginInvoke.
-Rick