异步将数据加载到数据网格中

Was*_*RAR 5 c# wpf datagrid asynchronous visual-studio

我在数据网格视图中加载了一些数据(1,200,000行),并且App花费了太多时间来加载并且有时冻结.

我不知道如何异步加载它们?(也许是progressBar).

我可以在这里找到一些帮助吗?

Sco*_*ger 5

我有一个应用程序,我正在使用线程做一些非常相似的事情.此代码应该在后台代码运行时一次更新一行数据网格.

using System.Windows.Threading;

private void Run()
{
    try
    {
        var t = new Thread(Read) { IsBackground = true };
        t.Start();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

private void Read()
{
    foreach (/* whatever you are looping through */)
    {
        /* I recommend creating a class for the result use that for the 
           datagrid filling. */
        var sr = new ResultClass()

        /* do all you code to generate your results */

        Dispatcher.BeginInvoke(DispatcherPriority.Normal, 
                               (ThreadStart)(() => dgResults.AddItem(sr)));   
    }    
}
Run Code Online (Sandbox Code Playgroud)


dth*_*rpe 3

将加载的数据分解为更小的块,例如一次 100 到 1000 行。如果 WPF 网格数据绑定到您的数据集合,并且该集合是可观察集合(实现 INotifyCollectionChanged),则当新数据添加到集合中时,WPF 将自动更新显示。

您还应该考虑将虚拟化列表控件或网格与分页数据源结合使用,以便仅加载当前显示在屏幕上的数据(而不是内存中的 120 万行数据)。这将为您执行“分块”,并使您能够以很少的内存使用或网络延迟向用户呈现基本上无限量的数据。

查看这篇关于虚拟列表框异步检索数据的文章:How do I populate a ListView in virtual mode asynchronously?