c# - c# 如何异步更新列表框?
问题描述
您好我正在尝试异步更新我的列表框,因此在更新时它不会冻结一秒钟,不幸的是它会引发异常
我的代码
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.
任何人都有线索,我该如何解决这个问题?
解决方案
跨线程是当您尝试从另一个线程(在您的情况下为任务)调用主线程的方法(在您的情况下为 UI 方法)时。
您可以从辅助线程询问该 UI 线程执行以下工作:
listBox1.Dispatcher.Invoke(() => {
listBox1.DataSource = listboxitems;
listBox1.TopIndex = listBox1.Items.Count - 1;
});
推荐阅读
- java - How to return multiple generated columns after insert in MyBatis(Oracle)
- java - for-each 不适用于表达式类型所需的数组或 java.lang.iterable
- spring-boot - Binding the select option list
- swift - UIStackView在collectionview布局内容跳转
- python - About what scatter plot is proportional?
- windows - JMeter.bat runs but doesn't start application
- mongodb - 如何获取父文档的所有字段?
- php - Laravel 5.7 php getimageinfo '无法打开流:没有这样的文件或目录'
- code-map - Expanding CodeMap as output from Architecture in vs2017
- lotus-notes - 使用 lotusscript 按钮保存副本文档并更改副本文档和原始文档的状态字段