static void Main(string[] args)
{
List<RandomWait> waiters = new List<RandomWait>();
for (int i = 0; i < 1000; i++)
{
waiters.Add(new RandomWait());
}
int counter = 0;
ParallelOptions options = new ParallelOptions();
CancellationTokenSource cancelToken = new CancellationTokenSource();
options.MaxDegreeOfParallelism = 15;
options.CancellationToken = cancelToken.Token;
Task.Factory.StartNew(() =>
{
Parallel.ForEach(waiters, options,
(waiter) =>
{
counter++;
Console.WriteLine(counter);
waiter.Pause();
counter--;
Console.WriteLine(counter);
});
});
Console.ReadLine();
cancelToken.Cancel();
Console.ReadLine();
}
public class RandomWait
{
public void Pause()
{
Random rnd = new Random();
Thread.Sleep(rnd.Next(2000));
}
}