Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

.net core 信号量 SemaphoreSlim #22

Open
ren8179 opened this issue Jan 11, 2021 · 0 comments
Open

.net core 信号量 SemaphoreSlim #22

ren8179 opened this issue Jan 11, 2021 · 0 comments

Comments

@ren8179
Copy link
Owner

ren8179 commented Jan 11, 2021

System.Threading.Semaphore 是Win32信号量对象(计数信号量)的包装, 是系统范围的信号量,因此可以在多个进程之间使用.

System.Threading.SemaphoreSlim 是CLR提供的一种轻量级的快速信号量,用于在预期等待时间很短的情况下在单个进程内等待。 SemaphoreSlim 类是用于在单个应用内进行同步的建议信号量。

如果需要有跨进程或AppDomain的同步时,可以考虑使用SemaphoreSemaphore是取得的Windows 内核的信号量,所以在整个系统中是有效的。它主要的接口是ReleaseWaitOne,使用的方式和SemaphoreSlim是一致的。

用信号量SemaphoreSlim代替锁

//Instantiate a Singleton of the Semaphore with a value of 1. This means that only 1 thread can be granted access at a time.
static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1,1);
//Asynchronously wait to enter the Semaphore. If no-one has been granted access to the Semaphore, code execution will proceed, otherwise this thread waits here until the semaphore is released 
await semaphoreSlim.WaitAsync();
try
{
    await Task.Delay(1000);
}
finally
{
    //When the task is ready, release the semaphore. It is vital to ALWAYS release the semaphore when we are ready, or else we will end up with a Semaphore that is forever locked.
    //This is why it is important to do the Release within a try...finally clause; program execution may crash or take a different path, this way you are guaranteed execution
    semaphoreSlim.Release();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant