基于Task定时检测网络本地网络状况
首先我们需要使用winInet.dll中的InternetGetConnectedState方法来检测本地是否连接网络,然后再通过ping的方式来获取网络状况。
然后我们采用Task来开辟一个线程来定时检测网络状况,最后自定义一个委托,然后用事件来简单的通知网络状况。
具体代码如下:
public class NetWorkHelper { /// <summary> /// 委托 /// </summary> /// <param name="flag"></param> /// <param name="msg"></param> public delegate void NetStatusDelegate(bool flag, string msg); public event NetStatusDelegate NetStatusEvent; public void StartCheck() { List<string> urlls = new List<string>() { "www.baidu.com", "www.sina.com", "www.cnblogs.com", "www.163.com", "www.csdn.com" }; Task.Run(async () => { await Task.Run(() => { while (true) { try { CheckServeStatus(urlls); } catch (Exception ex) { if (NetStatusEvent!=null) { NetStatusEvent(false, "网络异常"); } } finally { System.Threading.Thread.Sleep(3000); } } }); }); } // <summary> /// 检测网络连接状态 /// </summary> /// <param name="urls"></param> public void CheckServeStatus(List<string> urls) { int errCount = 0;//ping时连接失败个数 if (!LocalConnectionStatus()) { if (NetStatusEvent != null) { NetStatusEvent(false, "网络异常--->无连接"); } } else if (!MyPing(urls, out errCount)) { if ((double)errCount / urls.Count >= 0.3) { if (NetStatusEvent != null) { NetStatusEvent(false, "网络异常--->连接多次无响应"); } } else { if (NetStatusEvent != null) { NetStatusEvent(false, "网络异常--->网络不稳定"); } } } else { if (NetStatusEvent != null) { NetStatusEvent(false, "网络正常"); } } } private const int INTERNET_CONNECTION_MODEM = 1; private const int INTERNET_CONNECTION_LAN = 2; [System.Runtime.InteropServices.DllImport("winInet.dll")] private static extern bool InternetGetConnectedState(ref int dwFlag, int dwReserved); /// <summary> /// 判断本地的连接状态 /// </summary> /// <returns></returns> private static bool LocalConnectionStatus() { try { System.Int32 dwFlag = new Int32(); if (!InternetGetConnectedState(ref dwFlag, 0)) { Console.WriteLine("LocalConnectionStatus--未连网!"); return false; } else { if ((dwFlag & INTERNET_CONNECTION_MODEM) != 0) { Console.WriteLine("LocalConnectionStatus--采用调制解调器上网。"); return true; } else if ((dwFlag & INTERNET_CONNECTION_LAN) != 0) { Console.WriteLine("LocalConnectionStatus--采用网卡上网。"); return true; } } } catch (Exception ex) { } return false; } /// <summary> /// Ping命令检测网络是否畅通 /// </summary> /// <param name="urls">URL数据</param> /// <param name="errorCount">ping时连接失败个数</param> /// <returns></returns> public static bool MyPing(List<string> urls, out int errorCount) { try { bool isconn = true; Ping ping = new Ping(); errorCount = 0; try { PingReply pr; for (int i = 0; i < urls.Count; i++) { pr = ping.Send(urls[i]); if (pr.Status != IPStatus.Success) { isconn = false; errorCount++; } } } catch { isconn = false; errorCount = urls.Count; } return isconn; } catch (Exception ex) { throw new Exception(ex.ToString()); } } }