Listview没有响应Parallel.Forech循环 [英] Listview is not responding by Parallel.Forech loop

查看:65
本文介绍了Listview没有响应Parallel.Forech循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好.....



我有一个列表视图,我希望递归地显示一组数据...,我使用背景工作者保持我的用户界面活动..,我也使用Parallel.ForEach一次加载列表视图中的数据。



我的代码是:

Hi Everyone.....

I have a list view , where i want to show a collection of data recursively ..., I use back ground worker to keep my user interface active .., i also use Parallel.ForEach to load the data in list view at a time .

My code is:

public void bg_DoWork(object sender, DoWorkEventArgs e)
{

     Parallel.ForEach(this.listView1.Items.Cast<ListViewItem>(), list =>;
             {
                Function_ABCD(list);
             });
}





在我的Function_ABCD中,我通过添加大量的listviewitem来更新我的列表视图。我的问题是listview在执行时冻结。其他功能运行平稳意味着我可以最小化或最大化表单,停止执行等....



我怎样才能更新列表视图?



感谢你..



In my "Function_ABCD", i update my listview by adding huge number of listviewitem . my problem is that listview freezes when execution is going on.other function is running smoothly means i can minimize or maximize the form ,stop the execution etc....

how can i update the listview ?

Thanking You..

推荐答案



您正在尝试访问在主线程中创建的其他线程中的控件。您将从代码中获得的异常是跨线程异常。



请尝试以下代码:



Hi,
You are trying to access a control in other threads that was created in main thread. The exception you will get from your code is the Cross-thread exception.

Try the code below:

delegate void SetListviewItemsCallback(ListView.ListViewItemCollection listViewItems);

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    ProcessListView(listView1.Items);
}

public void ProcessListView(ListView.ListViewItemCollection listViewItems)
{
    if (listView1.InvokeRequired)
    {
        SetListviewItemsCallback d = new SetListviewItemsCallback(ProcessListView);
        this.Invoke(d, new object[] { listViewItems });
    }
    else
    {
        ListView.ListViewItemCollection items = listViewItems;
        Parallel.ForEach<ListViewItem>(items.Cast<ListViewItem>(), list =>
         {
             Function_ABCD(list);
         });
    }
}





当你从listView1中提取项目时,这将使你摆脱跨线程异常但是,当您将项目添加到



This will get you out of cross thread exception when you are extracting the items from listView1, however, you have to do similar thing when you add the items into your

Function_ABCD(ListViewItem item)

时,您必须执行类似的操作。您将通过多个线程访问Function_ABCD,将出现跨线程异常以及竞争条件;这将导致一个项目被多次添加,这将导致Argument异常。



我希望这会有所帮助。



问候

Jegan

. You will be accessing the "Function_ABCD" through multiple of thread, there will be cross thread exception as well as race condition; this will result in one item being added multiple of times which will cause an Argument exception.

I hope this helps.

Regards
Jegan


这篇关于Listview没有响应Parallel.Forech循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆