I'm looking for a fast and efficient implementation of a Semaphore for the .NET Compact Framework. There has been another Question here on SO (Semaphores in .NET compact framework) in which it was suggested to use P/Invoke, but this is not possible in the XNA Framework running on the XBox 360.
I can offer two implementations of my own, but both are sub-optimal, I believe.
Semaphore using an AutoResetEvent (pastebin)
One possible implementation of a managed Semaphore would, using an AutoResetEvent.
In this case, when work becomes available, the AutoResetEvent will transitioning only one thread into the 'runnable' state. When the OS thread scheduler runs the thread, it will reopen the AutoResetEvent, bringing the next thread into the 'runnable' state. So threads will be started sequentially, and only after their predecessor actually came to execution.
Semaphore using a ManualResetEvent (pastebin)
Another possible implementation would be using a ManualResetEvent.
In this case, when work becomes available, the ManualResetEvent will transition all threads into the 'runnable' state. All threads the OS thread scheduler runs compete for the work items until the first thread that runs out of work resets the ManualResetEvent again. In other words, possibly all threads will be woken for a short time even if not all threads are required.
Does anyone know of a better implementation out there or can provide suggestions for improving mine?