首页 > 解决方案 > 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.

任何人都有线索,我该如何解决这个问题?

标签: c#winformsasynchronousasync-awaitlistbox

解决方案


跨线程是当您尝试从另一个线程(在您的情况下为任务)调用主线程的方法(在您的情况下为 UI 方法)时。

您可以从辅助线程询问该 UI 线程执行以下工作:

listBox1.Dispatcher.Invoke(() => {
  listBox1.DataSource = listboxitems; 
  listBox1.TopIndex = listBox1.Items.Count - 1;
});

                       

推荐阅读