C# 如何使用Ping.SendAsync处理datagridview?

C# 如何使用Ping.SendAsync处理datagridview?,c#,.net,multithreading,network-programming,backgroundworker,C#,.net,Multithreading,Network Programming,Backgroundworker,我有一个应用程序,它ping datagridview中的每个IP,以编译响应IP RoundtripTime的列表。完成此步骤后,我将把RoundtripTime推回到datagridview ... foreach (DataGridViewRow row in this.gvServersList.Rows) { this.current_row = row; string ip = row.Cell

我有一个应用程序,它ping datagridview中的每个IP,以编译响应IP RoundtripTime的列表。完成此步骤后,我将把RoundtripTime推回到datagridview

    ...
        foreach (DataGridViewRow row in this.gvServersList.Rows)
        {
            this.current_row = row;

            string ip = row.Cells["ipaddr_hide"].Value.ToString();

            ping = new Ping();

            ping.PingCompleted += new PingCompletedEventHandler(ping_PingCompleted);

            ping.SendAsync(ip, 1000);

            System.Threading.Thread.Sleep(5);
        }
    ...

    private static void ping_PingCompleted(object sender, PingCompletedEventArgs e)
    {
        var reply = e.Reply;
        DataGridViewRow row = this.current_row; //notice here
        DataGridViewCell speed_cell = row.Cells["speed"];
        speed_cell.Value = reply.RoundtripTime;
    }
当我想使用DataGridViewRow row=this.current\u row;获取当前行,但我只得到一个错误关键字“this”在静态函数中不可用。那么,如何将该值推回datagridview

谢谢。

这是指当前实例。静态方法不是针对实例,而是针对类型。因此,没有这方面的资料

因此,需要从事件处理程序声明中删除static关键字。然后该方法将针对该实例

在尝试更新数据网格视图之前,您可能还需要将代码封送回UI线程-如果是这样,则需要类似以下内容的代码:

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;
    }
}

卡吉说的。但ping请求的结果可能会混淆,因为它们并没有连接到网格中的ip地址。无法判断哪个主机将首先响应,如果ping>5ms,则可能会发生任何情况,因为currentrow在两次回调之间发生变化。您需要做的是向回调发送datagridviewrow引用。为此,请使用SendAsync的重载:

ping.SendAsync(ip, 1000, row);
在回调中:

DataGridViewRow row = e.UserState as DataGridViewRow;

您可能还需要检查回复状态,以确保请求没有超时。

谢谢,这是我的一个简单方法!谢谢,我是c语言的初学者。这是一个使用委托的有用例子。