c# - 运行任务列表时出现 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
不确定这是否重要,但在AddLayer
for 循环中方法的末尾是一个作用于 GUI 控件的函数调用,所以我在函数调用中执行此操作:
private void AddLayer(string tableName)
{
//some work done here
Application.Current.Dispatcher.BeginInvoke((Action)(() => Map.Layers.Add(layer)))
}
解决方案
推荐阅读
- docker - 无法通过 NodeJS 查询/调用 Hyperledger Fabric Peers(在 docker swarm 网络中)-GRPC/S 截止日期错误
- javascript - 用状态反应条件渲染
- android - 如何在从 firebase 加载数据之前添加进度条,并在使用 firebasercycler 适配器从 firebase 加载数据后关闭此进度条
- javascript - 如何优化我的代码中的条件语句
- reactjs - 如何更新条件逻辑中的状态?
- php - MySQL 使用 JSON 编码查询 PHP/PDO
- android - (react-native-deep-link)使用传入链接问题触发应用程序(playstore url)
- python - Azure ratecard api filter by currency example
- python - Python 2 方式文本变量
- javascript - 如何在循环中一次启动一个ajax请求?