Asp.Net Core 实现异步操作锁
/设置同时访问线程最大数量
static SemaphoreSlim _semaphore = new SemaphoreSlim(4);
static void AccessDatabase(string name, int seconds)
{
Console.WriteLine($"{name} waits to access a database");
_semaphore.Wait();
Console.WriteLine($"{name} was granted an access to a database");
Thread.Sleep(TimeSpan.FromSeconds(seconds));
Console.WriteLine($"{name} is completed");
_semaphore.Release();
}
static void Main(string[] args)
{
for (int i = 1; i < 6; i++)
{
string threadName = $"Thread{i}";
int secondsToWait = 2 + 2 * i;
var t = new Thread(() => AccessDatabase(threadName, secondsToWait));
t.Start();
}
}
----------------------------------------
上面的代码 new 了一个 SemaphoreSlim 对象,设置访问线程最大数量为 4,开启 5 个线程,发现,
线程 5 一开始一直处于等待状态,直到线程 1 完成了,调用了 _semaphore.Release() 释放,线程 5 才能执行后面的代码