【发布时间】:2021-08-27 08:35:33
【问题描述】:
您好,我正在尝试异步更新我的列表框,因此更新时它不会冻结一秒钟,不幸的是它会引发异常
我的代码
private async void timer1_Tick(object sender, EventArgs e) {
await Task.Run(() =>
{
listBox1.DataSource = listboxitems;
listBox1.TopIndex = listBox1.Items.Count - 1;
});
}
例外
System.Reflection.TargetInvocationException:
InvalidOperationException: Invalid cross-thread operation: the listBox1 control was accessed by a different thread
than the thread for which it was created.
任何人都知道了,我该如何解决这个问题?
【问题讨论】:
-
除了更新
listBox1之外,您还在await Task.Run中执行其他操作吗?为了简单起见,您在此处删除了这些内容? -
仅使用任务/线程来收集数据,然后在 UI 线程中使用
BeginInvoke()委托,或者使用标准的IProgress<T>委托,在此处调用ListBox.BeginUpdate();,设置数据使用DataSource 属性或Items.AddRange()方法,然后是ListBox.EndUpdate(); -
Jimi - 你有这方面的例子吗(对于 AddRange)?我实际上遇到了同样的问题,但是有一个列表视图,这里的答案不完整,并且没有用于 winforms 列表视图的数据源属性(可能是因为它需要项目和子项目)
标签: c# winforms asynchronous async-await listbox