出现“索引超出范围"在C#中的List.Add()错误 [英] Got "Index out of bounds" Error on List.Add() in c#

查看:66
本文介绍了出现“索引超出范围"在C#中的List.Add()错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码

List<string> something = new List<string>();
Parallel.ForEach(anotherList, r =>
     {
            .. do some work
             something.Add(somedata);
      });

每百次运行大约1次,我得到 Index out of bounds 错误.反正有什么方法可以防止由线程引起的冲突(我认为)?

I get the Index out of bounds error around 1 time per hundred run. Is there anyway to prevent the conflict (I assume) caused by threading?

推荐答案

为了防止出现此问题,您可以使用

In order to prevent the issue, instead of List you may use ConcurrentQueue or similar Concurrent collections in your parallel part. Once the parallel task is done, you can put it in the List<T>.

有关更多信息,请查看System.Collections.Concurrent命名空间,以找到适合您的用例的集合.

For more information take a look at System.Collections.Concurrent namespace to find the suitable collection for your use case.

这篇关于出现“索引超出范围"在C#中的List.Add()错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆