【发布时间】:2011-06-11 12:40:47
【问题描述】:
我在让 Parallel.ForEach 正常工作时遇到问题。我有一个列表视图控件,可以将文件内容或多个文件内容(每个文件代表一个日志文件)加载到富文本框中。如果这一切都使用 Foreach 循环,但决定并行操作会在加载 100 多个文件时减少加载时间。
这是我用于 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;
【问题讨论】: