将参数传递给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
语句中传递BackgroundWorker
的DataGridView row
变量,然后在DoWork
方法中提取必要的数据。
上述就是C#学习教程:将参数传递给Backgroundworker分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/985188.html