I'm developing a simulation tool that performs various mathematical operations. So far I have not had the need to do parallel operations, but now I really need them. Among the various methods of parallelism I have read that best performance should be achieved using the Tasks.
I wrote this simple program, but I realized that something is wrong.
private static int taskCounter { get; set; }
private static void SimpleTest() { taskCounter--; }
static void Main(string[] args)
{
for (int N = 0; N < 100; N++)
{
taskCounter = 0;
List<Task> taskList = new List<Task>();
for (int i = 0; i < 100; i++)
{
taskCounter++;
Task task = Task.Factory.StartNew(() => SimpleTest());
taskList.Add(task);
}
Task.WaitAll(taskList.ToArray());
Console.WriteLine("Unsolved: {0}", taskCounter);
}
}
Expected: Unsolved: 0 for all iterations. Result:
[...]
Unsolved: 0
Unsolved: 0
Unsolved: 2
Unsolved: -4
Unsolved: -1
Unsolved: -1
Unsolved: 0
Unsolved: 0
Unsolved: 2
Unsolved: -1
[...]