Requirements: Due to the limited resources of the hardware, the program needs to consume a certain amount of hardware resources, in the case of high concurrency, if some methods that consume too much resources of the program are not restricted (exporting a large amount of data into an Excel table), it may affect the inability of the whole program to provide normal services, and also affect the normal operation of the operating system.
Semaphore and SemaphoreSlim Difference
SemaphoreSlim and Semaphore are similar in functionality. SemaphoreSlim is about 4 times faster than Semaphore, but SemaphoreSlim cannot be used for inter-process signaling.
The reason for the performance improvement is because the SemaphoreSlim class provides a lightweight alternative to the Semaphore class, which does not use the Windows kernel semaphore. Essentially, if you don't need to name semaphores, use the SemaphoreSlim class.
SemaphoreSlim is based on SpinWait and Monitor, so a thread waiting to get a lock consumes a period of CPU cycles, hoping to acquire the lock before giving way to another thread. If this doesn't happen, then the thread lets the system switch the context and try again when the OS schedules that thread again (by consuming some CPU cycles). If the wait is long, this mode can consume a lot of CPU cycles. So the best case for this implementation is that most of the time there is no waiting time and you can get the lock almost immediately. Semaphore relies on implementations in the OS kernel, so each time a lock is acquired, it takes quite a bit of CPU cycles, but after that the thread simply hibernates to get the time it takes to get the lock.
Semaphore Documentation:https://docs.microsoft.com/en-us ... aphore?view=net-6.0 SemaphoreSlim Documentation:https://docs.microsoft.com/en-us ... reslim?view=net-6.0
Before executing the method, the commonly used waiting methods are as followsCall according to the actual situation of your own business!
Wait(): Blocks the thread until it can enter SemaphoreSlim. Wait(0): The method will not be blocked. It will test the state of the waiting handle and return immediately. Wait: Blocks the current thread until it can enter SemaphoreSlim, while specifying a timeout using a 32-bit signed integer.
The source code is as follows:
The renderings are as follows:
|