代码之家  ›  专栏  ›  技术社区  ›  mustafabar

当我确定要同步访问不同的值引用时,为什么字典会崩溃?

  •  1
  • mustafabar  · 技术社区  · 16 年前

    在向字典添加键的过程中,如果我不锁定它并给出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);                
                }                                                       
            }
    
        }
    
    1 回复  |  直到 16 年前
        1
  •  0
  •   Willem van Rumpt    16 年前

    我将把添加到字典的操作移到并行循环之外。这为您节省了 lock (以一个额外的循环为代价),这使得在并行处理之前检查字典的内容至少更加实用。

    另外,你想要的是并行阅读,而不是增加字典。

    推荐文章