如何使用Ping.SendAsync与datagridview一起使用?
我有一个应用程序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’在静态函数中不可用。所以,如何将值推回到datagridview?
谢谢。
KAJ说的是什么。 但是有可能混淆ping请求的结果,因为它们没有连接到网格中的ip地址。 人们无法分辨出哪个主机会先响应,如果ping> 5ms,就会发生任何事情,因为currentntrow在回调之间发生变化。 您需要做的是将datagridviewrow引用发送到回调。 为此,请使用SendAsync的重载:
ping.SendAsync(ip, 1000, row);
并在回调中:
DataGridViewRow row = e.UserState as DataGridViewRow;
您可能还需要检查reply.Status以确保请求没有超时。
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; } }