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

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

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
}

}

Entry filed under: Uncategorized. Tags: .

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


My Pages

Blog Stats

  • 126 hits

Archives

Recent Posts

Tags


Follow

Get every new post delivered to your Inbox.