Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding Semaphore Class in .Net

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)

like image 618
Mubashar Avatar asked Feb 28 '23 15:02

Mubashar


2 Answers

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.

like image 81
Brian Rasmussen Avatar answered Mar 07 '23 20:03

Brian Rasmussen


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.

like image 38
Lucero Avatar answered Mar 07 '23 20:03

Lucero