Saturday, September 15, 2007

Multithreading with VB.NET Series - Part 1

So yes we all know that VB can now multithread with so much ease that we can get ourselves into trouble!! Tell m e about it, I was a victim of a naive assumption once which brought a SQL server to a grinding halt after it spawned 700 threads when a user press the damn button 7 times to make sure the 100 transactions went through!! The data was fine but the server was 'crying' for resources. Anyway that's another story...

So to create a new thread to do some work it a POC:

Dim th As New System.Threading.Thread(AddressOf MyLongRunningProc)
' Kick off that new thread to do some work
th.start


Private Sub MyLongRunningProc()
' Do the hard work here !!
End Sub

The questions that start to arise as you move into the world or asynchronous programming will soon start to pop up, due to most peoples affinity to synchronous programming mind set. So if two things are happening at once how do I keep track of progress, access shared data in a safe manner, etc. Well here MS has given us so many toys to play with, enter:
1. The Monitor,
2. The Mutex,
3. ReaderWriterLock
4. The Interlocked Type
5. The SyncLock Statement,
6. The Synchronization and MethodImpl Attributes,
7. VolatileRead/Write and MemoryBarrier,
8. The Semaphore Type.

So over the next few posts I will try to demystify so of these terms you may have heard about, but were to too afraid to use them. This should hopefully put some pretty cool tools into you toolbox to help you create those responsive applications you love to give to your clients, but also to make them more robust and safe :)

No comments: