Got a strange bug.
The output of following is:
RANGE: 100000 - 125000
RANGE: 100000 - 125000
RANGE: 100000 - 125000
RANGE: 100000 - 125000
And this is wrong!
If I add an extra local var
in the loop, the output is right!
int ax = i;
var curtask = Task.Run(() =>Work(ax, blocksize, size));
Output:
RANGE: 75000 - 100000
RANGE: 0 - 25000
RANGE: 25000 - 50000
RANGE: 50000 - 75000
(it's ok that the order isn't kept)
So the i
var is not given to the task on creation?
I find this situation very dangerous. Normally I would have trust in the parallels!
private static void Work(int startIndex, int blocksize, int maxSize)
{
int end = startIndex + blocksize;
Trace.WriteLine($"RANGE: {startIndex} - {end}");
Console.WriteLine($"RANGE: {startIndex} - {end}");
}
static void Main(string[] args)
{
int i = 0;
int size = 100000;
int blocksize = size/4;
int taskcount = 0;
var tasks = new List<Task>();
while (i < size)
{
//THIS WORKS!!!
//int ax = i;
//var curtask = Task.Run(() =>Work(ax, blocksize, size));
var curtask = Task.Run(() => Work(i, blocksize, size));
taskcount++;
tasks.Add(curtask);
i = i + blocksize;
}
Task.WaitAll(tasks.ToArray());
Console.WriteLine("DONE");
Console.ReadKey();
}