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