Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winforms asynchronous loading large data?

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?

like image 589
Donald N. Mafa Avatar asked May 04 '26 11:05

Donald N. Mafa


1 Answers

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
    }
}
like image 184
Daniel Johnson Avatar answered May 06 '26 02:05

Daniel Johnson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!