How to use Ping.SendAsync working with datagridview?

前端 未结 2 1915
囚心锁ツ
囚心锁ツ 2021-01-28 02:18

I have an application that pings every IP in the datagridview in order to compile a list of responsive IP RoundtripTime.When finished the step,I will push the RoundtripTime back

相关标签:
2条回答
  • 2021-01-28 02:46

    this refers to the current instance. A static method is not against an instance and instead just the type. So there is no this available.

    So you need to remove the static keyword from the event handler declaration. Then the method will be against the instance.

    You may also need to marshal the code back to the UI thread before trying to update the data grid view - if so then you'd need code something like the following:

    delegate void UpdateGridThreadHandler(Reply reply);
    
    private void ping_PingCompleted(object sender, PingCompletedEventArgs e)
    {
        UpdateGridWithReply(e.Reply);
    }
    
    private void UpdateGridWithReply(Reply reply)
    {
        if (dataGridView1.InvokeRequired)
        {
            UpdateGridThreadHandler handler = UpdateGridWithReply;
            dataGridView1.BeginInvoke(handler, table);
        }
        else
        {
            DataGridViewRow row = this.current_row; 
            DataGridViewCell speed_cell = row.Cells["speed"];
            speed_cell.Value = reply.RoundtripTime;
        }
    }
    
    0 讨论(0)
  • 2021-01-28 02:56

    What KAJ said. But there is a chance of mixing up results of ping requests because they are not connected to ip addresses in grid. One could not tell which host will respond first, and if there is a ping > 5ms anything can happen because currentrow is changing in between callbacks. What you need to do is to send a datagridviewrow reference to a callback. To do that, use an overload of SendAsync:

    ping.SendAsync(ip, 1000, row);
    

    And in a callback:

    DataGridViewRow row = e.UserState as DataGridViewRow;
    

    You might also want to check reply.Status to make sure that request did not time-out.

    0 讨论(0)
提交回复
热议问题