4

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)

casperOne
  • 73,706
  • 19
  • 184
  • 253
Mubashar
  • 12,300
  • 11
  • 66
  • 95

3 Answers3

4

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
  • 114,645
  • 34
  • 221
  • 317
3

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
  • 59,176
  • 9
  • 122
  • 152
  • :) 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 Feb 10 '10 at 10:13
1

Starting in .NET 4.0, you can use the SemaphoreSlim class if you have no requirement to wait across process boundaries.

Here is another discussion on choosing between the two.

Community
  • 1
  • 1
Pete Maroun
  • 2,045
  • 2
  • 18
  • 27