Fork me on GitHub

基于Task定时检测网络本地网络状况

首先我们需要使用winInet.dll中的InternetGetConnectedState方法来检测本地是否连接网络,然后再通过ping的方式来获取网络状况。

然后我们采用Task来开辟一个线程来定时检测网络状况,最后自定义一个委托,然后用事件来简单的通知网络状况。

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
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());
         }
     }
 
 }

  

posted @   黄高林  阅读(371)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示