简体   繁体   English

BackgroundWroker跨线程操作无效

[英]BackgroundWroker cross-thread operation not valid

I created a backgroundworker to fill a datagirdview. 我创建了一个背景工作人员来填充datagirdview。 The DatagridView is filled using a list which gets 2000 records from the table. DatagridView使用一个列表填充,该列表从表中获取2000条记录。 I used background worker to remove the non-responsive UI. 我使用后台工作程序删除了无响应的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. 跨线程操作无效:控件“ dgvBalanceSheet”从创建该线程的线程之外的线程访问。

How can I set the datagridView's datasource without getting these kind of errors? 如何设置datagridView的数据源而又不会出现此类错误?

You need to use the Completed event of BackgroundWorker: 您需要使用BackgroundWorker的Completed事件:

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. 请按照本教程中的步骤操作,以获取有关如何使用BackgroundWorker类的详细说明。

Use the ProgressChanged or RunWorkerCompleted callbacks on the background worker (similar to the DoWork event handling). 在后台工作ProgressChanged上使用ProgressChangedRunWorkerCompleted回调(类似于DoWork事件处理)。 This will then be done on the UI thread and you won't have the difficulties that show up now. 然后,这将在UI线程上完成,您将不会遇到现在出现的困难。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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