您好,我正在尝试异步更新我的列表框,所以更新时它不会冻结一秒钟,不幸的是它抛出了一个异常
我的代码
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.有谁有线索,我该怎么解决这个问题?
发布于 2021-06-10 18:37:01
跨线程是指当你试图从另一个线程(在你的例子中是Task线程)调用主线程(在你的例子中是UI线程)的方法时。
您可以从辅助线程中请求UI线程执行以下操作:
listBox1.Dispatcher.Invoke(() => {
listBox1.DataSource = listboxitems;
listBox1.TopIndex = listBox1.Items.Count - 1;
});https://stackoverflow.com/questions/67919397
复制相似问题