首页 > 解决方案 > 如何从异步任务将 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();
        }

标签: c#wpfasynchronous

解决方案


我认为你的例子是一个玩具例子,所以我只关注例外。发生这种情况是因为任务在与 UI 不同的线程上运行,并且您无法从非 UI 线程更新 UI 控件。

要从非 UI 线程与 UI 交互,请使用 Dispatcher:

// inside the non-UI thread
Dispatcher.Invoke(() => 
{
    MyDataGrid.ItemsSource = list;
});

推荐阅读