Overview: This code snippet demonstrates the Parrallel.invoke and the Parrallel.foreach. Parallel.foreach partions the reading of a collection into sections giving each thread a section of the whole collection. The Parallel.foreach can be canceled by the user.
private void DoSomething1(int iterations)
{
for(int i=0; i<iterations;i++)
{
Console.WriteLine("Do Something one");
Thread.Sleep(1000);
}
}
private void DoSomething2(int iterations)
{
for (int i = 0; i < iterations; i++)
{
Console.WriteLine("Do Something two");
Thread.Sleep(2000);
}
}
//The state.Break() exist out of the Parallel.ForEach loop when the
//application sets the cancelForEach boolean flag.
private void ProcessUsingParallelForEach(List<string> intCollection)
{
Parallel.ForEach(intCollection, (integer,state) =>
{
Console.WriteLine($"Parallel.Foreach={integer}");
if (cancelForEach==true) {
Console.WriteLine($"Exit Parallel.ForEach {integer}");
state.Break();
}
});
}
private bool cancelForEach = false;
[TestMethod]
public void TestThreadPooling()
{
int numberOfProcessors = Environment.ProcessorCount;
Parallel.Invoke(() => DoSomething1(5)
,()=>DoSomething2(10));
List<string> intCollection = new List<string>();
for (int i = 0; i < 500; i++)
{
intCollection.Add(i.ToString());
}
var TaskForEach=Task.Run(()=> ProcessUsingParallelForEach(intCollection));
Thread.Sleep(500);
cancelForEach = true;
Task.WaitAll(TaskForEach);
}