在我的算法中,我試圖做的是以下。c#並行For循環索引異常刪除元素後
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>>
}
的代碼是相當自我解釋,但我還是會嘗試進一步此詳述IR。
基本上我需要運行這個算法並比較代碼中顯示的值,如果漢明返回true,我必須將該值添加到'N'並將其從'R'中刪除,我必須將其刪除,因爲當下一個time while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while while run while'
如果有人需要了解更多,我可以進一步闡述。
我想要的是以某種多線程方式實現此目標,並且無例外地index out of range
或Argument exceptions
。
非常感謝。
ConcurrentBag'N'沒有任何擴展方法的'添加',我怎麼能添加項目呢? – touseef
仔細檢查你的代碼。你是否在代碼的頂部放置了'使用System.Collections.Concurrent;'? @touseef –
ConcurentBag有方法Add,https://msdn.microsoft.com/en-us/library/dd381779.aspx – MadOX