Can't get items in a ListView cross-thread

泄露秘密 提交于 2019-12-11 02:45:16

问题


My background worker needs to iterate through each item in a ListView. However I can't do this:

foreach (ListViewItem Item in List.Items)

because it's a cross thread operation.

I also can't put the items in a ListView.ListViewItemCollection and make the background worker read from that. This is still trying to access the ListView and creating a cross thread operation.

How can I make the ListView's items available to the background worker without putting them in a variable somewhere?


回答1:


Try using this function.

private delegate ListView.ListViewItemCollection GetItems(ListView lstview);

private ListView.ListViewItemCollection getListViewItems(ListView lstview)
{
    ListView.ListViewItemCollection temp = new ListView.ListViewItemCollection(new ListView());
    if (!lstview.InvokeRequired)
    {
        foreach (ListViewItem item in lstview.Items)
        temp.Add((ListViewItem)item.Clone());
        return temp;
    }
    else
        return (ListView.ListViewItemCollection)this.Invoke(new GetItems(getListViewItems), new object[] { lstview });
}

Call it like this:

foreach(ListViewItem item in getListViewItems(List))



回答2:


I agree with mdb, but have to mention that depending on importance of application,

Control.CheckForIllegalCrossThreadCalls = false;

can still be used as a temp quick fix.




回答3:


try this.

public Form1()
{
    InitializeComponent();

    Control.CheckForIllegalCrossThreadCalls = false;
}


来源:https://stackoverflow.com/questions/8022825/cant-get-items-in-a-listview-cross-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!