Some C# coding: semaphores
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);
}
}
}
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.
ReplyDeleteYour code is good though, I just thought I'd point it out.
Matheus,
ReplyDeleteIs this Semaphore implementation available on .NET 1.1?
Actually only on .Net 3...
ReplyDeletethanks for the code, I think taht's exactly what I need.