0 votes
by (2.0k points)
In C# there is the Semaphore and SemaphoreSlim type, which should I use if I'm just looking to implement a simple lock in my application?

1 Answer

0 votes
by (2.0k points)

Because you mentioned the fact you need a "simple" lock, have you thought about just using the lock keyword? If everything is contained within one method, often the C# lock is enough to get you going. 

But if you want to use Semaphore, while there are more differences between the two the *main* difference is that SemaphoreSlim can allow for synchronization within a single application, while a Semaphore can actually synchornize between different apps (On Windows). 

For example : 

Semaphore semaphore = new Semaphore(0, 1, "Global_MySemaphore");

This creates a Semaphore machine wide, allowing two different applications to actually synchornize and talk to each other. While this is pretty great, it's often overkill and that's why SemaphoreSlim was introduced to be a cut down version of just what you need if you only are working within a single app. 

Welcome to .NET Q&A, where you can ask questions and receive answers from other members of the community.
...