ディクショナリにキーを追加しているときに、ロックしないとクラッシュし、妥当な NullReferenceException が発生します
まれに、ディクショナリ値 (リスト参照) に要素を追加しているときにクラッシュすることもありますが、これは奇妙です...
私も別の質問があります。ファイルはテキスト形式です。それらを読み取るのに 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);
}
}
}