问题描述
下面是代码我有,但我不明白什么SemaphoreSlim正在做什么。
异步任务WorkerMainAsync()
{
SemaphoreSlim SS =新SemaphoreSlim(10);
名单,LT;任务> trackedTasks =新的List<任务>();
,而(DoMore())
{
等待ss.WaitAsync();
trackedTasks.Add(Task.Run(()=>
{
DoPollingThenWorkAsync();
ss.Release();
}));
}
等待Task.WhenAll(trackedTasks);
}
无效DoPollingThenWorkAsync()
{
变种味精=轮询();
如果(MSG!= NULL)
{
Thread.sleep代码(2000); //过程中长时间运行的CPU绑定工作
}
}
什么并等待 ss.WaitAsync(); &安培; ss.Release();
做
我想,如果我同时运行50个线程,然后编写代码,如 SemaphoreSlim SS =新SemaphoreSlim(10);
那么它将被强制运行在时间10个活动线程
在10线程之一。然后完成另一个线程将开始....如果我不对,然后帮我样的情况了解。
为什么伺机需要与<$ C一起使用$ C> ss.WaitAsync(); ?这是什么 ss.WaitAsync();
做
That is correct; the use of the semaphore ensures that there won't be more than 10 workers doing this work at the same time.
Calling WaitAsync
on the semaphore produces a task that will be completed when that thread has been given "access" to that token. await
-ing that task lets the program continue execution when it is "allowed" to do so. Having an asyncrhonous version, rather than calling Wait
, is important both to ensure that the method stays asynchronous, rather than being synchronous, as well as deals with the fact that an async
method can be executing code across several threads, due to the callbacks, and so the natural thread affinity with semaphores can be a problem.
A side note: DoPollingThenWorkAsync
shouldn't have the Async
postfix because it's not actually asynchronous, it's synchronous. Just call it DoPollingThenWork
. It will reduce confusion for the readers.
这篇关于需要了解SemaphoreSlim的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!