我的算法中,我想要做的是以下几点。
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循环运行时列表“R”应该更小,只有那些未满足上一个循环中Hamming条件的值才应该存在于R中。
如果有人需要更多理解,我可以进一步阐述。
我的目标是以某种多线程方式实现此目标,而不会出现“索引超出范围”或“参数异常”的异常。
提前感谢您的帮助。
TryTake
方法,我假设它会返回(以便将其添加到另一个集合中)并从源集合中删除对象。 - madoxdev