请用C#写一个判断网络连接断线重连的方法
时间: 2024-02-03 22:01:46 浏览: 37
以下是一个简单的判断网络连接断线重连的方法,使用System.Net.NetworkInformation命名空间中的Ping类来检测网络连接状态:
```csharp
using System;
using System.Net.NetworkInformation;
using System.Threading;
public static class NetworkConnectivityChecker
{
public static bool CheckNetworkConnectivity(string hostNameOrAddress, int timeout = 5000)
{
try
{
using (var ping = new Ping())
{
var reply = ping.Send(hostNameOrAddress, timeout);
return reply.Status == IPStatus.Success;
}
}
catch
{
return false;
}
}
public static void MonitorNetworkConnectivity(string hostNameOrAddress, int checkInterval = 5000, int timeout = 5000)
{
while (true)
{
if (!CheckNetworkConnectivity(hostNameOrAddress, timeout))
{
// 网络连接断开,执行重连操作
Console.WriteLine("网络连接已断开,正在尝试重连...");
// TODO: 执行重连操作
}
Thread.Sleep(checkInterval);
}
}
}
```
使用示例:
```csharp
// 检测网络连接状态
bool isConnected = NetworkConnectivityChecker.CheckNetworkConnectivity("www.baidu.com");
Console.WriteLine($"网络连接状态:{(isConnected ? "已连接" : "已断开")}");
// 监控网络连接状态,并在连接断开时执行重连操作
NetworkConnectivityChecker.MonitorNetworkConnectivity("www.baidu.com");
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)