将参数传递给Backgroundworker

我正在运行ac#代码与后台工作者。 我通过使用foreach循环并在循环内部传递foreach变量作为Backgroundworker的参数来强迫它。 但问题是每当我运行代码时只有单个随机值,很可能gridview中的最后一行作为参数传递。 代码如下

foreach (DataGridViewRow row in dataGridView3.Rows) { BackgroundWorker worker = new BackgroundWorker(); worker.WorkerSupportsCancellation = true; worker.DoWork += delegate { data = dataGridView3.Rows[row.Index].Cells[0].Value.ToString(); rowindex = row.Index; data1 = ros[0].Cells[0].Value.ToString(); }; worker.RunWorkerAync(); } 

尝试将参数作为row发送

 worker.DoWork += delegate(object s, DoWorkEventArgs args) { DataGridViewRow dgr = (DataGridViewRow)args.Argument; data = dataGridView3.Rows[dgr.Index].Cells[0].Value.ToString(); rowindex = dgr.Index; data1 = dgr[0].Cells[0].Value.ToString(); }; worker.RunWorkerAsync(row); 

除了@ Damith的答案,您还可以捕获本地范围中的foreach变量。

 foreach (DataGridViewRow row in dataGridView3.Rows) { DataGridViewRow copy = row; // captured! BackgroundWorker worker = new BackgroundWorker(); worker.WorkerSupportsCancellation = true; worker.DoWork += delegate { data = dataGridView3.Rows[copy.Index].Cells[0].Value.ToString(); rowindex = copy.Index; data1 = copy[0].Cells[0].Value.ToString(); }; worker.RunWorkerAync(); } 

这是因为row变量在每次迭代中绑定到不同的值,因此您在最后一次迭代时获得row的值。

这个答案以及Eric Lipperts博客都 对此进行了解释。

它看起来像线

 data = dataGridView3.Rows[row.Index].Cells[0].Value.ToString(); 

可以修改为:

 data = row.Cells[0].Value.ToString(); 

因为它有点违背了foreach陈述的全部目的。 此外,以下行似乎有一个拼写错误:

 data1 = ros[0].Cells[0].Value.ToString(); 

我不确定你想要包含的data1 ,但你可能只想考虑从foreach语句中传递BackgroundWorkerDataGridView row变量,然后在DoWork方法中提取必要的数据。