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