【发布时间】:2017-05-12 13:43:28
【问题描述】:
在我的算法中,我想做的是跟随。
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>>
}
代码很容易解释,但我仍然会在这里进一步详细说明。
基本上我需要运行这个算法并比较代码中显示的值,如果 hamming 返回 true,我必须将该值添加到“N”并将其从“R”中删除,我必须将其删除,因为下次外部 while 循环运行 List 'R' 应该更小,并且只有那些不满足循环运行中的汉明条件的值应该存在于 R 中。
如果有人需要了解更多,我可以进一步详细说明。
我想要的是以某种多线程方式实现这一目标,并且没有index out of range 或Argument exceptions 的例外。
非常感谢。
【问题讨论】:
标签: c# multithreading indexoutofboundsexception parallel.foreach