c#删除元素后的Parallel For Loop索引异常

标签 c# multithreading indexoutofboundsexception parallel.foreach

在我的算法中,我要做的是跟随。

while (R.Count > 0)
{
    //R is also  List<string>()   
    var N = new List<string>();
    var first = R[0];
    N.Add(first);
    R.Remove(first);
    //below commented code runs just fine but it takes a lot of time that is why i need to do multithreading to make it faster
    //for (int i = R.Count - 1; i >= 0; i--)
    //{
    //    if (hamming(first, R[i]))
    //    {   //hamming is a function just compare two strings and returns true or false.
    //        N.Add(R[i]);
    //        R.RemoveAt(i);
    //    }
    //}

    //Below is code of my attempt of multithreading the loop. I have tried it with foreach loop as well and it gives same error 'index out of range or argument exception'

    //ATTEMPT 1 :-
    Parallel.For(0,R.Count, i =>
    {

        if (hamming(first, R[i]))
        {
            N.Add(R[i]);
            R.RemoveAt(i);
        }
    });
    //ATTEMPT 2 :-
    Parallel.For(0,R.Count, i =>
    {

        if (hamming(first, R[i]))
        {
            N.Add(R[i]);
            R[i]="";
        }
    });
    var K = R.Where(a => a == "").ToList();
    var nc = cou - N.Count;
    //the value of 'K.Count' and 'nc' should be same here but I have checked in debugger its not the same.

    N_Total.Add(N);//this is just a List<List<string>>

代码非常 self 解释,但我仍将尝试在这里进一步阐述。

基本上我需要运行这个算法并比较代码中显示的值,如果汉明返回 true,我必须将该值添加到“N”并将其从“R”中删除,我必须删除它,因为下次外部 while 循环运行 List 'R' 应该更小,并且只有那些值应该出现在 R 中,这些值在之前的循环运行中不满足汉明条件。

如果有人需要了解更多,我可以进一步详细说明。

我想要的是以某种多线程方式实现这个目标,并且没有index out of rangeArgument exceptions 异常。

非常感谢。

最佳答案

首先List<string>不是 ThreadSafe这意味着它根本不应该用于并行操作。

试试看:ConcurrentBag<string>反而。

ConcurentBag存在于 System.Collections.Concurrent命名空间,其中包含更多的线程安全集合。


另一件事是:

你想在对它做任何事情之前确定该索引是否存在。


ConcurentBag可能有一些限制,也许值得检查该 namespace 中的其他集合:System.Collections.Concurrent因为那些是ThreadSafe .

https://msdn.microsoft.com/en-us/library/system.collections.concurrent.aspx

关于c#删除元素后的Parallel For Loop索引异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41359255/

相关文章:

c# - 用于格式化 C# 代码的 VS2010 扩展

c# - 线程完成后与UI线程通信

c++ - 从第二个线程访问主线程中的变量

c# - 索引在修剪文本处超出数组边界

c# - 使用 JSON.NET 获取 JSON 值的路径

c# - 使用 JSON.NET 在 C# 中进行无痛 JSON 反序列化

c# - 动态多对象锁定——多线程

C# 奇怪的索引越界异常

java - 查找字符串的所有子字符串 - StringIndexOutOfBoundsException

c# - 推荐一个关于Silverlight动画的好教程