简体   繁体   English

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

[英]Load data into a datagrid asynchronously

I'm loading in a datagrid view some data (1,200,000 rows), And the App is taking too much time to load and sometimes freezes. 我在数据网格视图中加载了一些数据(1,200,000行),并且App花费了太多时间来加载并且有时冻结。

I don't know how to load them asynchronously ? 我不知道如何异步加载它们? (with progressBar maybe). (也许是progressBar)。

Can I find some help here ? 我可以在这里找到一些帮助吗?

I have an application in which I'm doing something very similar using Threading. 我有一个应用程序,我正在使用线程做一些非常相似的事情。 This code should update your datagrid one line at a time while the code behind is running. 此代码应该在后台代码运行时一次更新一行数据网格。

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)));   
    }    
}

Break up the data loading into smaller chunks, say 100 to 1000 rows at a time. 将数据加载分解为更小的块,例如每次100到1000行。 If the WPF grid is databound to your data collection, and the collection is an observable collection (implements INotifyCollectionChanged), WPF will auto update the display as new data is added to the collection. 如果WPF网格数据绑定到您的数据集合,并且该集合是一个可观察的集合(实现INotifyCollectionChanged),WPF将在将新数据添加到集合时自动更新显示。

You should also consider using virtualized list controls or grids in conjunction with paging data sources, so that only the data that is currently shown on the screen will be loaded (instead of 1.2 million rows of data in memory). 您还应该考虑将虚拟列表控件或网格与分页数据源结合使用,以便仅加载屏幕上当前显示的数据(而不是内存中的120万行数据)。 This will perform the "chunking" for you and will enable you to present basically an infinite amount of data to the user with very little memory use or network lag. 这将为您执行“分块”,并使您能够以极少的内存使用或网络延迟向用户呈现基本上无限量的数据。

Check out this SO article on retrieving data asynchronously for a virtual listbox: How do I populate a ListView in virtual mode asynchronously? 查看有关虚拟列表框异步检索数据的SO文章: 如何异步填充虚拟模式下的ListView?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM