在向字典添加密钥期间,如果我不锁定它并给出合理的 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);
}
}
}