问题
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