Ok, I have a DataGridView that I’d like to load with data that I’m retrieving from a SQLDataReader running in a background worker as the data comes in (it’s a query that takes a long time).
My goal is for the user experience to be similar to searching for a file in Windows where the results appear in the list as they come in and you can still interact with the window.
I have it working with a background worker and data reader and I’m trying to add the row from the SQLDataReader.Read through using the BackgroundWorker.ReportProgress method. Everything technically works but the flicker is crazy and the form is unusable (probably not because the GUI thread is blocked but just because there’s so much going on…)
Any ideas? How do I make loading the datagridview “smooth”?
You will want to throttle the rate at which
ReportProgressis called. Do not call it for each row. Instead, queue up several rows and then callReportProgress. Tune it so that theProgressChangedevent is raised every couple of seconds.Honestly though, this is a scenario where I find that
BackgroundWorkerforces you into a bad design. What I would do is abandon theBackgroundWorkeraltogether and manually create a newThreadorTaskto do the loading. Have your worker thread queue the rows into aQueue<T>or some other data structure and then have your UI thread periodically poll this queue via aSystem.Windows.Form.Timeron whatever interval works best for you. The UI thread will extract a reasonable number of rows and place them in the grid that it does not try to do too much and hang up the UI or too little which would take forever.