Pass Parameter to thread problem
In a datagridview I have an IP address field. when I click on check status button I make thread for each row in datagridview and then call a remote object on the host on that IP and get some information and set another datagridview field as that info.
but there is a problem. the info is wrongly set on datagridview. why?
privat开发者_高级运维e void button_CheckStatus_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView.Rows.Count; i++)
{
IPAddress IP;
if (IsValidIP(dataGridView["IP", i].Value.ToString(), out IP))
{
Thread t = new Thread(() => CheckStatusThreadFunction(IP, i));
t.Start();
}
}
}
Make sure not to capture the loop variable:
for (int i = 0; i < dataGridView_VSD.Rows.Count; i++)
{
int ii = i;
IPAddress IP;
if (IsValidIP(dataGridView_VSD["VSD_IP", i].Value.ToString(), out IP))
{
Thread t = new Thread(() => CheckVSDStatusThreadFunction(IP, ii));
t.Start();
}
}
This is a very common mistake.
See e.g. here
精彩评论