c# - 如何从异步任务将 ItemsSource 添加到 DataGrid
问题描述
我有一个带有 Datagrid 的 WPF 应用程序。我希望能够运行每次 X 次从某个位置检索数据并更新 DataGrid ItemsSource 的代码。代码不能干扰 UI,所以它需要异步运行。我开始测试基础知识,但我还没有成功。我的测试编译,但抛出以下异常:WindowsBase.dll 中的“System.InvalidOperationException”。
我希望有人分享一个简单的方法来解决我认为应该是一个简单的问题。
public void runTask()
{
List<string> list = new List<string>();
int counter = 0;
Task.Run(async () =>
{
while (true)
{
list.Add(counter.ToString());
MyDataGrid.ItemsSource = list; // This is what I want to archive
counter++; // but I get this: Exception thrown: 'System.InvalidOperationException' in WindowsBase.dll
// Wait 2 seconds
await Task.Delay(2000);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
runTask();
}
}
}
// User starts the async task
private void Button_Click(object sender, RoutedEventArgs e)
{
runTask();
}
解决方案
我认为你的例子是一个玩具例子,所以我只关注例外。发生这种情况是因为任务在与 UI 不同的线程上运行,并且您无法从非 UI 线程更新 UI 控件。
要从非 UI 线程与 UI 交互,请使用 Dispatcher:
// inside the non-UI thread
Dispatcher.Invoke(() =>
{
MyDataGrid.ItemsSource = list;
});
推荐阅读
- c# - 如何从 C# 应用程序中获取 SSIS 项目参数列表
- c++ - 如何在 Microsoft Visual Studio 中启用“C++ 编译器”选项以将 C++ 编译器设置为 g++?
- javascript - 上午 11:40 到下午 12:20(11:40 < 12:20)之间的 Javascript 时间条件
- c++ - 通过指向基址的指针删除对象而不使用虚拟析构函数
- python-3.x - 将多个excel文件中的数据附加到一个excel文件中而不使用python pandas覆盖
- c# - 更改光标会影响以上所有内容
- python - 在张量中间执行 tf.signal.fft2d
- c# - Google - C# WinFormsApp - 身份验证
- c++ - 使用 goto 函数我的用户输入之一将不起作用(c++)
- python - 如何在pygame中射击子弹?