Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Parallel.ForEach和ListView控件_C#_.net_.net 4.0 - Fatal编程技术网

C# Parallel.ForEach和ListView控件

C# Parallel.ForEach和ListView控件,c#,.net,.net-4.0,C#,.net,.net 4.0,我在使Parallel.ForEach正常工作时遇到问题。我有一个listview控件,它将文件内容或多个文件内容(每个文件代表一个日志文件)加载到richtextbox中。所有这些都与Foreach循环一起工作,但决定在加载100多个文件时,并行操作将缩短加载时间 这是我用于foreach循环的代码块。我怎样才能得到一个平行的。每个工作 //Set cursor to WaitCursor Style this.Cursor = Cursors.WaitCursor; //Clear Mes

我在使Parallel.ForEach正常工作时遇到问题。我有一个listview控件,它将文件内容或多个文件内容(每个文件代表一个日志文件)加载到richtextbox中。所有这些都与Foreach循环一起工作,但决定在加载100多个文件时,并行操作将缩短加载时间

这是我用于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;
//将游标设置为WaitCursor样式
this.Cursor=Cursors.WaitCursor;
//清除文本框中的消息
this.rtbMessages.Clear();
//循环浏览每个选定的文件
foreach(lvMessageFiles.Items中的ListViewItem项)
{
//检查是否在listview中选择了项
if(Item.Selected&&rtbMessages.TextLength
不允许从非UI线程更新UI,非UI线程以
并行方式运行。ForEach
显然将是。相反,使用Invoke方法设置
rtbMessages
Text
,并调用
cvTimeline.ShowDate

<2您正在执行的操作存在的问题

1) 使用此特定代码,您试图从后台线程修改UI,这是不允许的
2) 无论如何,这个场景都不适合并行化,因为您的性能是“I/O绑定”到单个硬盘驱动器的。如果您想加快加载速度,可以将文件拆分到多个硬盘上,然后并行化可能是值得的


请参见

我遇到了德哈武的这个问题。。。无论如何,看看这篇博客文章。这对我来说非常简单,但它正是您想要实现的——在使用新的.NET4并行机制处理并发集合时更新UI。虽然不是为了每个人,而是为了任务


好的观点。。。由于所有这些文件都将在同一个驱动器上,甚至是文件夹上,并且没有对每个文件进行cpu密集型处理,因此并行化没有多大意义。这两个优点都很好,而且并行的顺序也不保证。ForEach因此所有日志文件都将以某种随机顺序排列