I'm fairly new to programming and decided to test out an idea I had involving asynchronous execution of array sorting tasks. I'm almost completely new to asynchronous programming and am running into an error that seems to only be explainable via some sort of strange asynchronous... stuff... occurring.
When I step through the following code to debug it, it works perfectly. When I allow it to run freely, however, I run into an Argument Out Of Range Exception: I becomes greater than allArrays.Count - 1, and the program fails. However, the
if (i >= allArrays.Count) Console.WriteLine($"i is too high! i = {i}");
line is never executed before it fails. Can someone explain this to me, and help possibly propose a solution to this issue?
Thank you!
//iterate while allArrays contains multiple arrays to be merged.
while (allArrays.Count > 1)
{
if (allArrays.Count % 2 != 0)//if it's not even, we add one and make it even, so every array has a partner!
{
allArrays.Add(new int[0]);
}
for (int i = 0; i < allArrays.Count - 1; i+=2)
{
Console.WriteLine($"i is {i}");
if (i >= allArrays.Count) Console.WriteLine($"i is too high! i = {i}");
mergeTasks.Add(Task.Run(() => Merge(allArrays[i], allArrays[i + 1])));
}
await Task.WhenAll(mergeTasks);
//empty the list of smaller arrays
allArrays.Clear();
//add results to all arrays then empty mergeTasks
mergeTasks.ForEach(r => allArrays.Add(r.Result));
mergeTasks.Clear();
}