Regarding the Semaphore class in .Net

I had a requirement to allocate the resource to the number of threads, so I used semaphores to handle all this, then I realized that the semaphore is used in case of blocking Interprocess resources. I googled and found some implementation of In-Process Semaphore and used this class, but it has some strange errors.

Now my question is: should I use the Dot Net semaphore class? and in any case, I can create a semaphore in the process and reduce the cost of interprocess (internal management)

+4
source share
3 answers

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

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

+4
source

If you are not a streaming guru, I would advise you to stick with famous working classes. So yes, stick with the .NET semaphore class if it works for your task.

Do not try to optimize your code unless you have a good reason for this (for example, profiling results).

However, if your code template is similar to the manufacturer-consumer template, effective solutions using the Monitor class that avoid using OS synchronization objects.

+3
source

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

Here is another discussion of the choice between them.

+1
source

Source: https://habr.com/ru/post/1300594/


All Articles