在添加字典的鍵時,如果我不鎖定它並給出合理的NullReferenceException,它會崩潰當我確定我正在同步訪問不同的值引用時,爲什麼Dictionary會崩潰?
當我向Dictionary Value(列表引用)添加元素時,它很少有時也會崩潰,很奇怪...
我還有一個問題。這些文件是文本格式。有時讀取它們需要1890毫秒,而其他時間則需要10倍以上。運行是連續的。是否有什麼突然
任何建議至少平抑這忙於在I/O緩衝成爲了可能......
private static void ParallelReadAndCalculate(FileInfo[] files)
{
Stopwatch sw1 = Stopwatch.StartNew();
while (!Parallel.ForEach(files, (FileInfo file) => ReadFileToEnd(file)).IsCompleted) ;
Console.WriteLine(sw1.ElapsedMilliseconds);
}
private static void ReadFileToEnd(FileInfo file)
{
string key = file.Name.Split('.')[0];
lock (ListOfCompanyData)
if (!ListOfCompanyData.ContainsKey(key))
{
ListOfCompanyData.Add(key, new List<string>(19800));
}
string line = "";
using (StreamReader streamReader = (new StreamReader(file.FullName)))
{
while ((line = streamReader.ReadLine()) != null) {
// this is giving KeyNotFoundException sometimes and others, do I need to lock here given the fact that I am accessing different references synchronously
ListOfCompanyData[key].Add(line);
}
}
}
你是否檢查過「key」被正確解析並插入?另外,你是否真的需要直接在構造函數中設置'List'的容量?我試圖讓框架處理那個。 – Bobby 2010-07-26 07:53:46