简体   繁体   中英

BackgroundWroker cross-thread operation not valid

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?

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.

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.

您无法从后台工作线程访问UIThread,在这种情况下,您可以在backgroundWorker完成后填充网格,因此可以将填充数据网格代码添加到worker_completed方法中,但是如果您想在工作进程进行时更新UI,则必须实现InvokerRequired,BeginInvoke模式

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM