Semaphore, 1. , .
var finished = new CountdownEvent(1);
var throttle = new Semaphore(3, 3);
foreach (WorkItem item in workitems)
{
finished.AddCount();
WorkItem capture = item;
ThreadPool.QueueUserWorkItem(
(state) =>
{
throttle.WaitOne();
try
{
ProcessWorkItem(capture);
}
finally
{
throttle.Release();
finished.Signal();
}
}, null);
}
finished.Signal();
finished.Wait();
WorkItem , , .
. Parallel.ForEach ParallelOptions.MaxDegreesOfParallelism, concurrency.
var options = new ParallelOptions();
options.MaxDegreeOfParallelism = 3;
Parallel.ForEach(workitems, options,
(item) =>
{
ProcessWorkItem(item);
});
1 , ThreadPool Semaphore . . , .