首页 > 解决方案 > 运行任务列表时出现 System.ArgumentOutOfRangeException

问题描述

我有一个在 for 循环中对 ~20 个对象运行的方法。我希望循环的每次迭代都使用新任务执行该方法,以防止 GUI 在工作发生时停止。但是,我注意到在创建任务后立即System.ArgumentOutOfRangeException在输出中出现错误。最终,整个应用程序崩溃了System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index'

我的第一个想法是这是循环中的一个简单错误,当前迭代索引不匹配,但事实并非如此。

这是我的循环:

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

不确定这是否重要,但在AddLayerfor 循环中方法的末尾是一个作用于 GUI 控件的函数调用,所以我在函数调用中执行此操作:

private void AddLayer(string tableName)
{
    //some work done here
    Application.Current.Dispatcher.BeginInvoke((Action)(() => Map.Layers.Add(layer)))
}

标签: c#wpftask

解决方案


推荐阅读