Multithreading in VB.NET
If you are new to VB.NET SchoolThis is the 14th in the series of lessons in the VB.NET School. The VB.NET School is a kind of interactive learning platform where those who want to learn .NET with VB.NET can find help and support. With one issue a week, describing some areas of the VB.NET Programming Language with the Microsoft .NET Platform, this is not the same traditional passive tutorial where the author only writes and the reader only reads. There will be exercise problems at the end of each issue, which the reader is expected to solve after reading the issue. The solution to these problems will be provided in the next issue for testing purposes. There is also a dedicated message board attached with the school, where you can ask questions about the article, and the author will respond to your question within 2/3 days. You can send your suggestions, feedback or ideas on how these lessons can be improved to either the Author (farazrasheed@acm.org) or the WEBMASTER (info@programmersheaven.com).
For previous lessons click here
Lesson Plan
In this lesson we will learn how to achieve multithreading in VB.NET and .NET. We will start out by looking at what multithreading is and why we need it. Later we will demonstrate how we can implement multithreading in our VB.NET applications. Finally, we will learn about the different issues regarding thread synchronization and how VB.NET handles them.
What is Multithreading
Multithreading is a feature provided by the operating system that enables your application to have more than one execution path at the same time. We are all used to Windows' multitasking abilities, which allow us to execute more than one application at the same time. Just right now I am writing the 14th lesson of the Programmers Heaven's VB.NET School in Microsoft Word, listening to my favorite songs in WinAmp and downloading a new song using the Internet Download Manager. In a similar manner, we may use multithreading to run different methods of our program at the same time. Multithreading is such a common element of today's programming that it is difficult to find windows applications that don't use it. For example, Microsoft Word takes user input and displays it on the screen in one thread while it continues to check spelling and grammatical mistakes in the second thread, and at the same time the third thread saves the document automatically at regular intervals. In a similar manner, WinAmp plays music in one thread, displays visualizations in the second and takes user input in the third. This is quite different from multitasking as here a single application is doing multiple tasks at the same time, while in multitasking different applications execute at the same time.
Author's Note: When we say two or more applications or threads are running at the same time, we mean that they appear to execute at the same time, i.e. without one waiting for the termination of the other before starting. Technically, no two instructions can execute together at the same time on a single processor system (which most of us use). What the operating system does is divides the processor's execution time amongst the different applications (multitasking) and within an application amongst the different threads (multithreading).
Just consider the following small program:
Imports SystemModule Test
Public Sub Main()
Fun1()
Fun2()
Console.WriteLine("End of Main()")
End Sub
Public Sub Fun1()
Dim i As Integer
For i = 1 To 5
Console.WriteLine("Fun1() writes: {0}", i)
Next
End Sub
Public Sub Fun2()
Dim i As Integer
For i = 10 To 6 Step -1
Console.WriteLine("Fun2() writes: {0}", i)
Next
End Sub
End Module
The output of the program is: Fun1() writes: 1
Fun1() writes: 2
Fun1() writes: 3
Fun1() writes: 4
Fun1() writes: 5
Fun2() writes: 10
Fun2() writes: 9
Fun2() writes: 8
Fun2() writes: 7
Fun2() writes: 6
End of Main()
Press any key to continue
As we can see, the method Fun2() only started its execution when Fun1() had completed its execution. This is because when a method gets called, the execution control transfers to that method. And when the method returns the execution starts from the very next line of the code that called the method. i.e. the program implicitly has only one execution path. Using multithreading, we can define multiple concurrent execution paths within our program called threads. For example, we can use threads so that the two methods Fun1() and Fun2() may execute without waiting for each other to terminate.
Multithreading in VB.NET
The .NET Framework, and thus VB.NET provides full support for multiple execution threads in a program. You can add threading functionality to your application by using the System.Threading namespace. A thread in .NET is represented by the System.Threading.Thread class. We can create multiple threads in our program by creating multiple instances (objects) of this class. A thread starts its execution by calling the specified method and terminates when the execution of that method gets completed. We can specify the method name that the thread will call when it starts by passing a delegate of the ThreadStart type in the Thread class constructor. The delegate System.Threading.ThreadStart may reference any method which has the void return type and which takes no arguments.
Public Delegate Sub ThreadStart()For example, we can change our previous application to run the two methods in two different threads like this:
Dim firstThread As New Thread(New ThreadStart(AddressOf Fun1)) Dim secondThread As New Thread(New ThreadStart(AddressOf Fun2))Here we have created two instances of the Thread class and passed a ThreadStart type delegate in the constructor which references a method in our program. It is important that the method referenced in the Thread class constructor, through the ThreadStart delegate is parameter-less and has no return type. A thread does not start its execution when its object is created. Rather, we have to start the execution of a thread by calling the Start() method of the Thread class.
firstThread.Start() secondThread.Start()
Here we have called the Start() method of the firstThread, which in turn will call the Fun1() method in a new thread. However this time the execution will not halt until the completion of the Fun1() method, but will immediately continue with the next statement which also starts the execution of the Fun2() method in a new thread. Again, the main thread of our application will not wait for the completion of the Fun2() method and will continue with the following statement. The complete source code for the application is:
Imports SystemImports System.ThreadingModule Test
Public Sub Main()
Dim firstThread As New Thread(New ThreadStart(AddressOf Fun1))
Dim secondThread As New Thread(New ThreadStart(AddressOf Fun2))
firstThread.Start()
secondThread.Start()
Console.WriteLine("End of Main()")
End Sub
Public Sub Fun1()
Dim i As Integer
For i = 1 To 5
Console.WriteLine("Fun1() writes: {0}", i)
Next
End Sub
Public Sub Fun2()
Dim i As Integer
For i = 10 To 6 Step -1
Console.WriteLine("Fun2() writes: {0}", i)
Next
End Sub
End Module
One possible output of the program is: End of Main()
Fun1() writes: 1
Fun1() writes: 2
Fun1() writes: 3
Fun1() writes: 4
Fun1() writes: 5
Fun2() writes: 10
Fun2() writes: 9
Fun2() writes: 8
Fun2() writes: 7
Fun2() writes: 6
Press any key to continue
Why did we say 'one possible output'? The reason is that we can't be sure about the execution sequence of the threads. Thread switching is completely Operating System dependent and may change each time you execute the program. Here what we notice is that the Main() thread ended before the start of any of the other two threads. However, after that the two functions seem to be calling in a sequence. What we might have expected was loop iterations of the two methods coming in a mixed way. So why didn't we get that output? In fact, the methods Fun1() and Fun2() have such short execution times that they get finished even before the switching of the two threads for a single time. If we increase the loop counters of these methods, we may notice the threads in execution.
School Home
|
|
Dr.Di
From New Zealand (Report as abusive) |
Good one! This is a comment about the "Threading" lesson (14). It's really good one with good examples (honestly, I didn't try to run them :)) Probably it was a best tutorial on threading in VB.Net I could find on Internet. Probably I'd made one addition to the lesson. As follows from the text, " The delegate System.Threading.ThreadStart may reference any method which has the void return type and which takes no arguments. " That's right. But many readers would ask: "What if I want to pass some parameters to a method been run in a different thread? And get a result?" I believe, the answer isn't so obvious for unskilled audience. Of course, the answer is easy: just to put all "input" and "output" parameters into a declaration section, or even better to wrap the method and all parameters as properties into a separate class. VB.NET School - really good place! :) |
|
Anonymous
(Report as abusive) |
Great Article The most concise article in one place on threading I have seen. |
|
John
(Report as abusive) |
Awesome Very good and clear explanation of how to use Treading. The examples are easy to follow and understand as well. Great! |
|
Anonymous
(Report as abusive) |
Thank you soooo much! This article really explains how threads work and how to control them. Thank you so much! |
|
Anonymous
(Report as abusive) |
return types good article,but what about functions that have other return types than void ? |
| View all Rate and comment this article |
Sponsored links
Check For Updates
Easily add update features to your applications. A complete .Net updating solution.
Easily add update features to your applications. A complete .Net updating solution.
Build IT Knowledge with Current & Trusted Content
Helps Employees Develop & Hone New Technical Programming Skills. Sign Up & Get Full Access.
Helps Employees Develop & Hone New Technical Programming Skills. Sign Up & Get Full Access.
Check Out IT Certification Preparation Materials
Sign Up With SkillSoft & Get Access to Training Materials for Over 50 Professional Certifications.
Sign Up With SkillSoft & Get Access to Training Materials for Over 50 Professional Certifications.
Villanova University Six Sigma & IT Certificate Programs
100% Online programs in Six Sigma, IS Security, CISSP Prep, Business Analysis, Proj. Mgmt. and more!
100% Online programs in Six Sigma, IS Security, CISSP Prep, Business Analysis, Proj. Mgmt. and more!
.Net Localization in three simple steps (WYSIWYG)
Localize .Net, C#/C/C++ & Delphi apps visually. HTML, HTML Help, XML & databases. Try Sisulizer now!
Localize .Net, C#/C/C++ & Delphi apps visually. HTML, HTML Help, XML & databases. Try Sisulizer now!
