想象一下有几个任务同时尝试使用资源池。资源池中的单个资源只能被特定数量的任务同时使用;这个数字可以是一。
在同步环境中,我认为
在同步环境中,我认为
WaitHandle.WaitAny
& Semaphore
是正确的选择。var resources = new[] { new Resource(...), new Resource(...) }; // 'Resource' custom class wrapers the resource
var semaphores = new[] { new Semaphore(1, 1), new Semaphore(1, 1) };
...
var index = WaitHandle.WaitAny(semaphores);
try
{
UseResource(resources[index]);
}
finally
{
semaphores[index].Release();
}
但是在异步环境下,我们应该怎么做呢?