How to use simple multi-threading in C#.net

In this article I will attemp to tell you my experiences programming with threads as a novice.

First of all, I really understand that using threads instead of classical one-thread approach is similar to

juggling several balls in your hand. There are many challenges awaits : You cannot access windows form components in threads, parameter passing is somewhat unhandy and sharing variables are nightmares.

I searched over internet to find valuable information on threads and found a really simplicity without using so much classes and complex implementations like mutex, semphore and monitors.

It is hidden in lock keyword !
If you do not want your threads in a racing condition simply use lock keyword to lock the code inside that block, so only one single thread may access it. The rule of the game is so simple which can be seen in following example :
using System.Threading;

private Object dummy;  // our dummy lock variable

int sharedVariable; // so called, trouble shared variable

private void threadFunction() // spawned thread

{

lock (stackLock)
{
sharedVariable++;  // critical se
}

}

May 26, 2009 at 3:57 pm Leave a comment


My Pages

Blog Stats

  • 126 hits

Archives

Recent Posts

Tags


Follow

Get every new post delivered to your Inbox.