【问题标题】:How to use Ping.SendAsync working with datagridview?如何使用 Ping.SendAsync 与 datagridview 一起工作?
【发布时间】:2012-04-02 15:27:37
【问题描述】:

我有一个应用程序 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_row; 获取当前行但我得到一个错误关键字'this' is not available in static function.so,如何将值推回datagridview?

谢谢。

【问题讨论】:

    标签: c# .net multithreading network-programming backgroundworker


    【解决方案1】:

    this 指的是当前实例。静态方法不是针对实例,而是针对类型。所以没有可用的this

    因此,您需要从事件处理程序声明中删除 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;
        }
    }
    

    【讨论】:

    • 谢谢,我是c#的初学者。这是我使用委托的有用示例。
    【解决方案2】:

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

    ping.SendAsync(ip, 1000, row);
    

    在回调中:

    DataGridViewRow row = e.UserState as DataGridViewRow;
    

    您可能还想检查 reply.Status 以确保该请求没有超时。

    【讨论】:

    • 谢谢,我的方法很简单!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    • 2023-02-02
    • 2021-12-19
    • 2012-05-29
    • 2018-05-17
    • 2014-08-16
    相关资源
    最近更新 更多