Pass Parameter to thread

In datagridview, I have an IP address field. when I click the check status button, I make a stream for each row in the datagridview, and then call the remote object on the host at this IP address and get some information and set another datagridview field as this information.

but there's a problem. information is incorrectly set on datagridview. why?

    private 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();
            }
        }

    }
+3
source share
1 answer

Be sure not to write a 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 here

+2
source

Source: https://habr.com/ru/post/1771721/


All Articles