Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# semaphore.CurrentCount在此上下文中如何工作?_C#_Multithreading_Semaphore - Fatal编程技术网

C# semaphore.CurrentCount在此上下文中如何工作?

C# semaphore.CurrentCount在此上下文中如何工作?,c#,multithreading,semaphore,C#,Multithreading,Semaphore,我刚开始学习信号量lim,但是在这个程序中,semaphore.CurrentCount是如何递增和递减的呢?据我所知,当调用semaphore.Wait()时,释放计数器递减1,当semaphore.release()时,允许执行两个线程,但是semaphore.CurrentCount如何递增?它是从0开始还是从1开始 var semaphore = new SemaphoreSlim(2, 10); for (int i = 0; i < 20; i+

我刚开始学习
信号量lim
,但是在这个程序中,semaphore.CurrentCount是如何递增和递减的呢?据我所知,当调用
semaphore.Wait()
时,释放计数器递减1,当
semaphore.release()
时,允许执行两个线程,但是
semaphore.CurrentCount
如何递增?它是从0开始还是从1开始

        var semaphore = new SemaphoreSlim(2, 10);
        for (int i = 0; i < 20; i++)
        {
            Task.Factory.StartNew(() =>
            {
                Console.WriteLine("Entering task " + Task.CurrentId);
                semaphore.Wait(); //releasecount--
                Console.WriteLine("Processing task " + Task.CurrentId);
            });
        }

        while (semaphore.CurrentCount <= 2)
        {
            Console.WriteLine("Semaphore count: " + semaphore.CurrentCount);
            Console.ReadKey();
            semaphore.Release(2);
        }
        Console.ReadKey();
var信号量=新信号量lim(2,10);
对于(int i=0;i<20;i++)
{
Task.Factory.StartNew(()=>
{
Console.WriteLine(“输入任务”+task.CurrentId);
semaphore.Wait();//releasecount--
Console.WriteLine(“处理任务”+task.CurrentId);
});
}

虽然(semaphore.CurrentCount
Wait
递减,而
Release
递增。

该信号灯就像一个具有一定容量的房间。使用SemaphoreSlim,您可以指定初始容量和最大容量。在达到最大容量后,任何人都不能再进入房间。离开房间的每件物品中,只有一个i他被允许进入

CurrentCount获取可以进入文件室的剩余线程数

    for (int i = 0; i < 20; i++)
    {
        Task.Factory.StartNew(() =>
        {
            Console.WriteLine("Entering task " + Task.CurrentId);
            semaphore.Wait(); //only from 2 - 10 threads can be at the time
            Console.WriteLine("Processing task " + Task.CurrentId);
        });
    }
for(int i=0;i<20;i++)
{
Task.Factory.StartNew(()=>
{
Console.WriteLine(“输入任务”+task.CurrentId);
semaphore.Wait();//一次只能从2-10个线程开始
Console.WriteLine(“处理任务”+task.CurrentId);
});
}
这里呢

while (semaphore.CurrentCount <= 2) 
while(semaphore.CurrentCount