2011-01-19 45 views
1

我有一個問題讓Parallel.ForEach正常工作。我有一個列表視圖控件,用於將文件內容或多個文件內容(每個文件表示一個日誌文件)加載到richtextbox中。如果這一切都與Foreach循環一起工作,但決定並行操作將減少加載100多個文件時的加載時間。Parallel.ForEach和ListView控件

這是我用於foreach循環的代碼塊。我如何獲得Parallel.Foreach的工作?

//Set cursor to WaitCursor Style 
this.Cursor = Cursors.WaitCursor; 

//Clear Messages RichTexBox 
this.rtbMessages.Clear(); 

//Loop through each selected file 
foreach (ListViewItem Item in lvMessageFiles.Items) 
{ 
    //Check if item is selected in the listview 
    if (Item.Selected && rtbMessages.TextLength < rtbMessages.MaxLength) 
    { 
     //Get Path to message file 
     filename = String.Format("{0}\\Data\\Log\\{1}.log", Global.AppPath, Item.SubItems[0].Text); 

     //Set Timeline Events calendar to selected items created date 
     cvTimeline.ShowDate(Convert.ToDateTime(lvMessageFiles.SelectedItems[0].SubItems[2].Text)); 

     //Check if file exists 
     if (File.Exists(filename)) 
     { 
      //streamreader to read the file 
      reader = new StreamReader(filename); 

      //to copy the read content in to richtextbox 
      string MessageContents = String.Format("{0}\n{1}\n", ("file:///" + filename.Replace(" ", "%20").Replace("\\", "/")), reader.ReadToEnd()); 
      rtbMessages.Text += MessageContents; 

      // closing streamreader 
      reader.Close(); 
     } 
    } 

} 

//Set cursor to WaitCursor Style 
this.Cursor = Cursors.Default; 

回答

0

不允許你從一個非UI線程,哪些線程在Parallel.ForEach顯然將更新UI。而是使用Invoke方法設置TextrtbMessages並致電cvTimeline.ShowDate

3

2您在做什麼問題。

1)與此特定代碼,您試圖從不允許
2)這種情況下是不是並行化的很好的候選人,無論如何,因爲你表現都非常後臺線程修改UI「I/O綁定「到單個硬盤。如果你想加快加載時間,將文件分割到多個硬盤驅動器,然後並行可能是值得

看到Is Parallel File.Read Faster than Sequential Read?

+0

好點......因爲所有這些文件將是相同的驅動器,甚至是文件夾,並且在每個文件,它並沒有多大意義,並行化的無CPU密集型處理。 – 2011-01-19 04:46:11