开发者

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜