WinForms的异步加载大量数据?加载、数据、WinForms

2023-09-03 21:50:37 作者:玻璃心珍珠泪

我刚刚收到一个bug列表中的旧的应用程序开发耶年前,我需要理清事情之一是它需要加载过程的数据整合到一个屏幕上,时间量,而屏幕是冻结的,不幸的是,这是在的WinForms .NET 4.5。的数据加载到一个WinForms DataGridView中。我想看看是否有任何方式加载使用C#5异步和等待这些数据,同时刷新网格添加下一组数据。这可能是同时或滚动在background.Any想法?

I just received a bug list for an old app developed yeah years ago and one of the things i need to sort out is the amount of time it takes to load data into one screen,of course, while the screen is frozen and unfortunately this is in WinForms .NET 4.5. The data is loaded into a WinForms DataGridView. I would like to find out if there is any way of loading this data using C# 5 async and await,while refreshing the grid to add the next set of data. It may be while scrolling or in the background.Any ideas?

推荐答案

尝试从一个异步线程加载所有的数据到一个数组,然后使用调用插入数组复制到DataGridView的。

Try loading all of the data into an array from an asynchronous thread and then using Invoke to insert the array into the DataGridView.

从的Form_Load调用此

Call this from Form_Load

new Thread(new ThreadStart(Run)).Start();

然后建立这个方法

then create this method

private void Run()
{
    //DataArray

    //Load Everything into the DataArray

    Invoke(new EventHandler(delegate(object sender, EventArgs e) 
    {
        //Load DataArray into DataGridView
    }), new object[2] { this, null });
}

这我认为是最优化的方式来加载的东西变成一个控制,因为控制是不允许的MainThread以外的被感动。我不知道为什么微软加强了这一点,但他们做的。可能有一种方法来使用反射MainThread外修改控件。

This I believe is the most optimized way to load something into a Control since Controls are not allowed to be touched outside of the MainThread. I don't know why Microsoft enforces this but they do. There may be a way to modify Controls outside of the MainThread using Reflection.

您可以额外慢慢地将数据加载到DataGridView中。这将需要更长的时间来加载所有的数据,但它可以让你继续使用的形式,而它加载。

You could additionally slowly load the data into DataGridView. It will take longer to load all of the data but it will allow you to continue to use the Form while it is loading.

private void Run()
{
    //DataArray

    //Load Everything into the DataArray

    for(/*Everything in the DataArray*/)
    {
        Invoke(new EventHandler(delegate(object sender, EventArgs e) 
        {
            //Load 1 item from DataArray into DataGridView
        }), new object[2] { this, null });
        Thread.Sleep(1); //This number may have to be tweeked
    }
}