标签:current 访问 总线 oid 线程 task 多个 eating for
当有多个线程同时访问有限制的资源时会出现并发情况,此时可以使用‘信号量’来控制访问资源的线程数量
static void Main(string[] args)
{
int taskCount = 10;//总线程数
int seatCount = 4;//资源访问最大线程数量
var semaphore = new SemaphoreSlim(seatCount,6);
var tasks = new Task[taskCount];
for (int i = 0; i < taskCount; i++)
{
tasks[i] = Task.Run(() => TaskRun(semaphore));
}
Task.WaitAll(eatings);
Console.WriteLine("All Tasks have finished!");
}
static void TaskRun(SemaphoreSlim semaphore)
{
semaphore.Wait();
try
{
Console.WriteLine("Task {0} is Running!", Task.CurrentId);
Thread.Sleep(1000);
}
finally
{
Console.WriteLine("Task {0} have finished!", Task.CurrentId);
semaphore.Release();
}
}
标签:current 访问 总线 oid 线程 task 多个 eating for
原文地址:https://www.cnblogs.com/getpower/p/10308129.html