【问题标题】:Parallel.ForEach and ListView ControlParallel.ForEach 和 ListView 控件
【发布时间】: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;

【问题讨论】:

    标签: c# .net .net-4.0


    【解决方案1】:

    2 你在做什么的问题。

    1) 使用此特定代码,您正在尝试从不允许的后台线程修改 UI
    2)无论如何,这种情况都不是并行化的好选择,因为您的性能是“I / O绑定”到单个硬盘驱动器。如果您想加快加载时间,请将文件拆分到多个硬盘驱动器上,然后并行化可能是值得的

    Is Parallel File.Read Faster than Sequential Read?

    【讨论】:

    • 好点......因为所有这些文件都将位于同一个驱动器甚至文件夹上,并且每个文件都没有CPU密集型处理,因此并行化它没有多大意义。
    • 这两个优点,Parallel.ForEach 也不保证顺序,所以所有日志文件的顺序都会有点随机
    【解决方案2】:

    您不能从非 UI 线程更新 UI,Parallel.ForEach 中的线程显然会更新。而是使用Invoke方法设置rtbMessagesText,调用cvTimeline.ShowDate

    【讨论】:

      【解决方案3】:

      我正在经历这个问题的dejavu......无论如何,看看这篇博客文章。这对我来说非常简单,但完全符合您的目标 - 在使用新的 .NET 4 并行机制处理并发集合时更新 UI。虽然不是 ForEach 而是 Task。

      http://blogs.msdn.com/b/csharpfaq/archive/2010/06/18/parallel-programming-task-schedulers-and-synchronization-context.aspx

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多