Winforms asynchronous loading large data?

烂漫一生 提交于 2019-12-07 15:29:41

问题


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?


回答1:


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

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

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.

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



回答2:


You want to use virtual mode. Other solutions do all the upfront work to load the data and then put it into the grid (which still gives you a startup delay), or else they add chunks of data at a time (which messes up your scrolling).

Virtual mode reverses this; instead of you throwing your data at the grid, virtual mode will have the grid request your data.



来源:https://stackoverflow.com/questions/17500613/winforms-asynchronous-loading-large-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!