Some C# coding: semaphores

Sunday, July 23, 2006 3 Comments

AFAIK there is no Semaphore implementation in .NET. Today I needed a semaphore to implement some of the new functionality of a new subsystem (more on this later this week).

I played a little bit with it and here it is the tiny semaphore C# code. I wonder if is correct...


class Semaphore
{
object mLock = new object();
long mCount = 0;

void Enter()
{
lock( mLock )
{
while( mCount == 0 )
{
Monitor.Wait(mLock);
}
--mCount;
}
}

void Release()
{
lock( mLock )
{
++mCount;
Monitor.Pulse(mLock);
}
}
}

3 comments:

  1. Actually, you might have found this by now but there is a Semaphore class on System.Threading namespace in addition to many other classes you can use if you need thread synchronization like ReaderWriterLock and Mutex.
    Your code is good though, I just thought I'd point it out.

    ReplyDelete
  2. Matheus,

    Is this Semaphore implementation available on .NET 1.1?

    ReplyDelete
  3. Actually only on .Net 3...
    thanks for the code, I think taht's exactly what I need.

    ReplyDelete