I have a method being run on ~20 objects in a for loop. I want each iteration of the loop to perform the method with a new task to prevent the GUI from stalling while the work is happening. However, I noticed right after a task is created I get a System.ArgumentOutOfRangeException
error in the output. Eventually, the entire app crashes with System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index'
.
My first thought was it was a simple error in the loop with the current iteration index not matching up, but that isn't the case.
Here's my loop:
Collection<string> tableNames = GetTableNames(path); //just gets a collection of strings
var tasks = new List<Task>();
for (int i = 0; i < tableNames.Count; i++)
{
var addTask = Task.Run(() => { AddLayer(tableNames[i]); });
tasks.Add(addTask);
}
await Task.WhenAll(tasks);
ResumeRefresh(); //I want this to be called after all the tasks complete
Not sure if this is important but at the end of the AddLayer
method in the for loop is a function call that acts on a GUI control, so I do this at the function call:
private void AddLayer(string tableName)
{
//some work done here
Application.Current.Dispatcher.BeginInvoke((Action)(() => Map.Layers.Add(layer)))
}