To wait for a semaphore in C#, you can use the WaitOne method of the SemaphoreSlim or Semaphore class.
Here is an example using SemaphoreSlim:
main.cs113 chars5 lines
In this example, a SemaphoreSlim object is created with an initial count of 0. The Wait()
method is then called, which will block the current thread until the semaphore becomes available. Once the semaphore is available, the method will return and the thread can continue executing.
Alternatively, you can also use the WaitOne()
method of the Semaphore class:
main.cs111 chars5 lines
In this example, a Semaphore object is created with an initial count of 0 and a maximum count of 1. The WaitOne()
method is then called, which works the same as Wait()
in the SemaphoreSlim example.
Both SemaphoreSlim and Semaphore are used for thread synchronization and can be useful in scenarios where you need to limit the number of threads that can access a resource at the same time.
gistlibby LogSnag