Click here to Skip to main content
15,879,239 members
Articles / Programming Languages / Visual Basic
Article

Introduction to making multithreaded VB.NET Apps

Rate me:
Please Sign up or sign in to vote.
4.47/5 (60 votes)
17 Jun 20038 min read 291.4K   79   23
The basics on how to take advantage of VB's new (as of .NET) facilities for threading in your application.

Introduction

Back in the days of VB 6 and earlier, writing a multithreaded VB application was hard. MS even told ambitious VB developers not to do it, the hacks required were not going to be supported, endorsed, blessed, etc. No soup for you.

With the release of VB.NET, we VB developers finally get to play. I'll take you through the basics to get you started. Once you have made your first multithreaded application, you will officially be 'dangerous.'

I've done my best to keep my explanations straightforward and accessible, but be forewarned that multi-threading has a few hairy issues to grapple with, it will probably take a couple reads through this article and some tinkering in VB.NET before the topics I touch on here make thorough sense. Besides that, we're mearly scratching the surface of many of the concepts and techniques that VB.NET supports. When you are ready for more, MSDN is a good place to start.

What is a Thread?

Threads are like employees at a company. In your typical company, each employee can be working at the same time. The company is the process which contains all the threads working in it, and which organizes them towards a common purpose. When you write an application and run it, you are starting a process with a single thread. So, your application can do one thing at a time (it's a company with one employee). Your variables and objects are like the copier and fax in an office...some things are global and shared by everyone in a company while others are private, residing in the office of one person or department.

A modern operating system allows you to run a number of programs at the same time, each of which has one or more threads. If you have one processor in your machine, these processes (aka applications) and their threads aren't necessarily running at the exact same time. Typically the OS let's the first process run on the CPU for a fraction of a second, then it let's the next one run for a fraction of a second, and so on, creating the illusion than lots of things are happening at the same time. When the OS let's a process run, that process then gets to decide which thread it wants to give time to first, then it gives time to the next, etc, much as the OS does with processes.

However, with certain recent processors, and with multi-processor machines running a multiprocessor aware operating system like Win2k or WinXP it is possible for two processes and possibly two or more of their threads to be running at the exact same time.

Why Use Multithreading?

Multithreading is useful for a number of reasons. Your application may need to respond to external events. When the external event happens, it creates a new thread to handle it appropriately without preempting freezing the rest of your application. If you have a timer control in your VB.NET app, guess what? You have a multithreaded application!

I've used threads in my applications to handle tasks in the background without freezing up my application's interface while things are processing. When the task is done, it updates a variable in my application so the main thread will be able to tell that it's done.

You may be writing a service that need to keep track of several different things at the same time. Threads let you juggle a lot of tasks and events simultaneously.

One Fax At a Time

Having two threads working at exact same time is great! But like the employees that try to stuff paper into the shared fax machine at the exact same time, threads can cause problems when they use shared resources.

Let's say you have a global variable called "intWebHits" that helps your program track the number of hits to your website. And let's say you are running two threads that do the same thing, each tracking a different part of the website but recording hits to the same global variable:

VB.NET
Sub IncrementWebCount()
    intWebHits += 1
    Console.WriteLine(intWebHits)
End Sub

Each time either thread gets a hit, it prints out the total number of hits so far and then it increments intWebHits. What happens if you get 2 web hits at the same time? On a machine that can run 2 threads at the same time, you could end up running each line of the above code with each thread at the exact same time. So if the total for intWebHits were "129" before the simultaneous hits, both threads would run that first line of code at the same time, both incrementing the total and both printing "131" OR both printing "130" depending on factors outside your control or ability to reliably predict. What you wanted was 130 then 131; instead you got 130 and 130 or 131 and 131. If you have a machine that can only run one thread at a time, you could still be in trouble. What if you run line 1 on the first thread, then that thread is paused and the second thread is given the CPU to run on for its share of time? It will run its copy of line 1. Then it will run line 2. Then the first thread gets its turn again. It run's its copy of line 2. What is your output? 131 and 131. Again, not what you wanted. This behavior may be fairly harmless with a webcounter, but you can probably imagine writing programs where being off by 1 here and there is not acceptable.

The wise people that make operating systems and compilers recognized this problem and they have provided us with a way of dealing with it: resource locks. A resource lock allows a thread to claim control of a variable and to be guaranteed that no other thread will have a lock or be able to do anything to that locked resource at the same time as the thread that has placed a lock on it. Any other thread that needs access to that variable just has to wait its turn. It even works with multiprocessor system.

VB.NET
Sub IncrementWebCount()
    SyncLock objMyLock
        intWebHits += 1
        Console.WriteLine(intWebHits)
    End SyncLock
End Sub

Now when those threads run at the same time, they will each try to get a lock on the object "objMyLock" but only one will get it, the other one will wait until the lock is off "objMyLock" before it will run. BTW, objMyLock can by any object you care to use for a lock.

But these locks have problem of their own. Consider the following:

VB.NET
Sub IncrementWebCountA()
    SyncLock objMyLockA
        SyncLock objMyLockB
            intWebHits += 1
            Console.WriteLine(intWebHits)
        End SyncLock
    End SyncLock
End Sub

Sub IncrementWebCountB()
    SyncLock objMyLockB
        SyncLock objMyLockA
            intWebHits += 1
            Console.WriteLine(intWebHits)
        End SyncLock
    End SyncLock
End Sub

Notice that we have two slightly different routines. The first routine tries to get a lock on objMyLockA first and then it tries for a lock on objMyLockB. The second routine tries for a lock on B, then on A. If these two routines were to run at the same time, the first routine would get a lock on objMyLockA at the same time that the second routine would get a lock on objMyLockB. The first routine needs a lock on objMyLockB in order to continue. The second routine needs a lock on A. They both have something the other needs to continue, but neither will give up the lock it holds until it gets the lock it needs to complete. So, these threads would essentially stop working. This is what's known as a race condition. You don't want one of these...so be careful not to have interlocking locks like that in your code. These examples are simple, but if you have locks all over you application and routine calling other routines from within a lock protected area of code, you can end up with this problem without it being something as easy to identify on a read through as it was here.

And one more thing. Some objects and structures built in to .NET are multithread safe (they don't require a lock to function, though you may still need one depending on how you use it) and some are not. Integers are multithread safe, so you can read and write them with two different threads at the same time, but you could have issues like those we talked about earlier...it may not give you an error, but it probably isn't going to behave in the way you were hoping for either. Collections, as an example, are not multithread safe. If you have two threads try to read a collection at the same time, you will most likely get an error. The .NET documentation usually tells you if something is thread safe.

If it's an option, run routines in your thread that don't access shared variables at all. You won't need locks and you won't have to worry about avoiding or debugging race conditions! The issues related to shared variables and the order in which threads are running are know collectively as "Thread Synchronization" issues.

Cut To The Chase

Now that you know to avoid using shared variable without locks, and to avoid race conditions whenever you use locks, you are ready for the code!

VB.NET
Dim thrMyThread As New System.Threading.Thread( _
    AddressOf IncrementWebCountA)
thrMyThread.Start()

Yah, that's it. These two lines create a new thread running the IncrementWebCountA routine. You can set the priority of the thread and do other cool things with it, but that's the basic usage right there. One point to note is that the starting routine must require no parameters in order to be used to start a thread.

Whenever you run a program in VB, you specify a "startup object" like form1. That's where your "main" thread begins...the one that starts your application, sets up the forms, sets up the global variables, etc. It's your first employee. Will you add more? :)

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
Scott is a producer with Electronic Arts in Redwood City and he's an amateur coder.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Shahin Khorshidnia26-Mar-12 23:30
professionalShahin Khorshidnia26-Mar-12 23:30 
GeneralThanx ist very helpful Pin
manoharmind16-Mar-12 21:19
manoharmind16-Mar-12 21:19 
GeneralMy vote of 5 Pin
alialikh2-Dec-10 18:24
alialikh2-Dec-10 18:24 
GeneralImage App hangs with high CPU and a true thread question Pin
rfrank535614-May-10 11:06
rfrank535614-May-10 11:06 
GeneralRe: Image App hangs with high CPU and a true thread question Pin
changoh27-May-10 10:02
changoh27-May-10 10:02 
Generalhelp me pls Pin
ehsan500011-Apr-10 12:12
ehsan500011-Apr-10 12:12 
Questiongrrrr, someone please tell me what is wrong with this Pin
tstivers199027-Jun-09 9:03
tstivers199027-Jun-09 9:03 
QuestionHow Can Access Public Object into Two Different Thread Pin
Bhushan Badhe26-May-09 23:42
Bhushan Badhe26-May-09 23:42 
AnswerRe: How Can Access Public Object into Two Different Thread Pin
changoh27-May-10 9:57
changoh27-May-10 9:57 
GeneralMultiThreaded function Pin
tomsmaily12315-Jun-06 7:44
tomsmaily12315-Jun-06 7:44 
GeneralConsole Pin
naveenieus26-Apr-06 20:34
naveenieus26-Apr-06 20:34 
Generalmultithreading Pin
Prasun Hazra 24-Apr-06 2:14
Prasun Hazra 24-Apr-06 2:14 
Generalexecuting project automatically checking time Pin
divyaaruna23-Mar-06 21:30
divyaaruna23-Mar-06 21:30 
GeneralExcel VB Pin
Anonymous9-Sep-05 12:06
Anonymous9-Sep-05 12:06 
General"This is what's known as a race condition." Pin
Anonymous8-Apr-05 9:46
Anonymous8-Apr-05 9:46 
Generalunicode1201&codpage1256 Pin
Anonymous9-Mar-04 0:58
Anonymous9-Mar-04 0:58 
Generaluni code support in vb.net Pin
ch_faf16-Oct-03 1:46
ch_faf16-Oct-03 1:46 
GeneralRe: uni code support in vb.net Pin
Scott Bonds16-Oct-03 14:52
Scott Bonds16-Oct-03 14:52 
AnswerRe: uni code support in vb.net Pin
parkavimahendran1-Nov-07 1:56
parkavimahendran1-Nov-07 1:56 
AnswerRe: uni code support in vb.net Pin
parkavimahendran1-Nov-07 1:57
parkavimahendran1-Nov-07 1:57 
GeneralComments Pin
dog_spawn18-Jun-03 8:42
dog_spawn18-Jun-03 8:42 
This article explains what multithreading is, which is welcome for beginners. The problem is you don't really explain what syncronization options are available in .NET. Are you going to do a second part?
GeneralRe: Comments Pin
Scott Bonds18-Jun-03 12:24
Scott Bonds18-Jun-03 12:24 
GeneralRe: Comments Pin
Matthew Morrison12-Dec-06 1:06
Matthew Morrison12-Dec-06 1:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.