不能在ListView交叉线程中获取项
本文关键字:获取 线程 ListView 不能 | 更新日期: 2023-09-27 18:13:40
我的后台工作者需要遍历ListView中的每个项目。但是我不能这样做:
foreach (ListViewItem Item in List.Items)
因为它是一个跨线程操作
我也不能把项目放在ListView中。ListViewItemCollection并让后台worker从中读取。这仍然在尝试访问ListView并创建一个跨线程操作。
我怎么能使ListView的项目提供给后台工作人员,而不把它们放在一个变量的地方?
尝试使用此函数
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 });
}
这样写:
foreach(ListViewItem item in getListViewItems(List))
我同意mdb,但必须提到,根据应用程序的重要性,
控制。CheckForIllegalCrossThreadCalls = false;
仍然可以用作临时的快速修复。
试试这个
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}