Tuesday, October 24, 2006

C# equivalent CSingleLock / Critical Section  [Digg.com This!]

C# has a pretty nifty way to perform critical section locking using the newly created 'lock' statement. For those of you after the quick answer:

Object lockobj = new Object();
lock (lockobj)
{
// Do your locked work
}

To offer a bit more information..

When would you use this?

Critical sections are used when you need to operate on objects, files, or other resources such as database and TCP connections across a number of threads.

If you have multiple threads all trying to write to a file at the same time, for instance (say a log file), what happens if threads try writing at the same time? One thread may get an exception saying it cannot open the file, or worse you may end up losing data if you don't correctly catch the exception.

How does it work?

Quite simply the lock statement will check if the object is locked and if it is it will wait. Once the existing lock is relinquished the waiting thread will then move into the code within the braces and perform its operations.

If you want the full technical details please visit the MSDN.

0 Comments:

Post a Comment

<< Home