Reputation: 1085
I created a backgroundworker to fill a datagirdview. The DatagridView is filled using a list which gets 2000 records from the table. I used background worker to remove the non-responsive UI.
private BackgroundWorker worker;
worker = new BackgroundWorker() { WorkerReportsProgress = true };
worker.DoWork += worker_DoWork;
worker.RunWorkerAsync();
void worker_DoWork(object sender, DoWorkEventArgs e)
{
var listAccGroups = vwAccVoucherDetails.ToList(); // vwAccVoucherDetails is the table containing records.
dgvBalanceSheet.DataSource = listAccGroups;
}
The error I am getting is:
Cross-thread operation not valid: Control 'dgvBalanceSheet' accessed from a thread other than the thread it was created on.
How can I set the datagridView's datasource without getting these kind of errors?
Upvotes: 0
Views: 2311
Reputation: 1064
You can not access UIThread from background worker thread, in this case you can fill the grid after backgroundWorker completed, so you can add filling datagrid code into worker_completed method, but in cases you want to update UI when worker in progress, you have to implement InvokerRequired, BeginInvoke Pattern
Upvotes: 0
Reputation: 78545
You need to use the Completed event of BackgroundWorker:
BackgroundWorker worker = new BackgroundWorker() { WorkerReportsProgress = true };
worker.DoWork += worker_DoWork;
worker.Completed += worker_Completed;
worker.RunWorkerAsync();
void worker_DoWork(object sender, DoWorkEventArgs e)
{
e.Result = vwAccVoucherDetails.ToList(); // vwAccVoucherDetails is the table containing records.
}
void worker_Completed(object sender, RunWorkerCompletedEventArgs e) {
dgvBalanceSheet.DataSource = e.Result;
}
Follow the steps in this tutorial for detailed instructions on how to use the BackgroundWorker class.
Upvotes: 3
Reputation: 3280
Use the ProgressChanged
or RunWorkerCompleted
callbacks on the background worker (similar to the DoWork
event handling). This will then be done on the UI thread and you won't have the difficulties that show up now.
Upvotes: 0