private void run() { while (!stopPing) { PServerModel psm = null; try { if (pQueue.Count > 0) { psm = pQueue.Dequeue(); Ping pSender = new Ping(); PingOptions option = new PingOptions(); option.DontFragment = true; var ipArray = System.Net.Dns.GetHostAddresses(dt.Rows[psm.Index]["地址"].ToString()); if (ipArray != null && ipArray.Length > 0) { string ip = ipArray[0].ToString(); byte[] buffer = new byte[128]; PingReply reply = pSender.Send(ip, 5000, buffer, option); if (reply.Status == IPStatus.Success) { psm.Success = true; psm.Delay = (int)(reply.RoundtripTime); rQueue.Enqueue(psm); } else { psm.Success = false; psm.Delay = 9999; psm.LastMessage = "失败:" + reply.Status; rQueue.Enqueue(psm); } } else { psm.Success = false; psm.Delay = 9999; psm.LastMessage = "无法解析"; rQueue.Enqueue(psm); } } System.Threading.Thread.Sleep(50); } catch (Exception ex) { if (null == psm) { return; } psm.Success = false; psm.Delay = 9999; psm.LastMessage = ex.Message; rQueue.Enqueue(psm); } } }
private void check() { while (!stopPing) { PServerModel psm = null; try { if (rQueue.Count > 0) { psm = rQueue.Dequeue(); if (psm.Success) { dt.Rows[psm.Index]["成功次数"] = dt.Rows[psm.Index].IsNull("成功次数")?1: Convert.ToInt32(dt.Rows[psm.Index]["成功次数"]) + 1; } else { dt.Rows[psm.Index]["失败次数"] = dt.Rows[psm.Index].IsNull("失败次数")?1: Convert.ToInt32(dt.Rows[psm.Index]["失败次数"]) + 1; } dt.Rows[psm.Index]["PING次数"] = dt.Rows[psm.Index].IsNull("PING次数")?1: Convert.ToInt32(dt.Rows[psm.Index]["PING次数"]) + 1; dt.Rows[psm.Index]["最后信息"] = psm.LastMessage; dt.Rows[psm.Index]["延迟"] = psm.Delay; } else { System.Threading.Thread.Sleep(100); } if (pQueue.Count < 1) { for (int i = 0; i < dt.Rows.Count; i++) { PServerModel psma = new PServerModel { Delay = 0, Index = i, Success = false }; pQueue.Enqueue(psma); } } } catch (Exception ex) { if (psm != null) { dt.Rows[psm.Index]["最后信息"] = psm.LastMessage + "\r\n" + ex.Message; } } } }
private void button1_Click(object sender, EventArgs e) { stopPing = false; for (int i = 0; i < dt.Rows.Count; i++) { PServerModel psm = new PServerModel { Delay = 0, Index = i, Success = false }; pQueue.Enqueue(psm); } for (int i = 0; i < 10; i++) { Task tsk = new Task(run); tsk.Start(); } Task stsk = new Task(check); stsk.Start(); button1.Enabled = false; }