2010-07-26 8 views
1

在添加字典的鍵時,如果我不鎖定它並給出合理的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);     
      }              
     } 

    } 
+0

你是否檢查過「key」被正確解析並插入?另外,你是否真的需要直接在構造函數中設置'List'的容量?我試圖讓框架處理那個。 – Bobby 2010-07-26 07:53:46

回答

0

我會移動增加了字典中的並行循環之外。這爲您節省了一個lock(以一個額外的循環爲代價),並且使其在並行處理之前檢查詞典的內容至少更加實用。

此外,它是你想要並行完成的閱讀,而不是添加到字典中。

+0

我同意你的意見,而且我已經這麼做了。我只是想知道背後的概念。閱讀時也會發生錯誤。請檢查代碼 中的評論感謝您的回答 – mustafabar 2010-07-26 09:33:52

+0

從提供的代碼看起來確實很奇怪。 有幾個問題:是否有其他進程在運行?如何定義「ListOfCompanyData」?當拋出KeyNotFoundException時,你看到「key」的值是什麼嗎? – 2010-07-26 09:57:45

相關問題