views:

326

answers:

3

Dear Gurus

I had a requirement to allocate the resource to number of threads so i used semaphores to handle all this then i realized that semaphore are used in case of Interprocess locking of resources. I googled and found some implementation of In-Process Semaphore and used that class but it has some weird bugs.

Now my question is Should i use Dot Net Semaphore Class?? and is there anyway i can create in process semaphore and reduce the cost of interprocess (internal management)

+3  A: 

If you're not a threading guru, I'd advise you to stick with known working classes. So yes, stick to the .NET semaphore class if it works for your task.

Don't micro-optimize your code unless you have a valid reason to do so (e.g. profiler results).

That said, if your code pattern is something like a producer-consumer pattern, there are efficient solutions using the Monitor class which avoid the use of OS synchronization objects.

Lucero
+1 Monitor FTW!
dboarman
:) Well, being a server developer i have to be master on these things i think i have a good control on these but to avoid chances of bugs i myself hesitate to write custom code. Before this i was using a custom implemented using waitevents but it had couple of bugs. So i now moved back to Semaphore Class. Can you tell me what is the Cost of OS Semaphore object so i can calculate Effort/Gain.
Mubashar Ahmad
A: 

The semaphore class in the Threading namespace of .NET is for threads, not for multiple processes.

MSDN:Limits the number of threads that can access a resource or pool of resources concurrently.

Semaphore objects do also exist on the Windows/OS level, but I doubt that you are using them. Which namespace are you using/refering to?

weismat
If you name the semaphore it because a system level semaphore and thus available between processes.
Brian Rasmussen
I missed that - I was just aware of the two concepts and was not aware that .Net can also control the system semapore.
weismat
Yes, That is why I added this Question :)
Mubashar Ahmad
+2  A: 

The Semaphore class has a number of constructors. Some of the overloads allow you to specify a name. Naming the Semaphore instance makes it a system level semaphore available to other processes. If you don't need that just use one of the other constructors. IIRC there still a kernel object associated with the instance though.

See http://msdn.microsoft.com/en-us/library/e1hct27h.aspx.

Brian Rasmussen