gpt4 book ai didi

C# 如何检测互联网连接/断开(带有事件)?

转载 作者:太空宇宙 更新时间:2023-11-03 12:19:39 27 4
gpt4 key购买 nike

我编写的这段代码完美运行,但我担心每 2 秒执行一次 ping 操作会消耗太多资源,或者可能导致互联网连接出现一些问题。

        new Thread(() =>
{
if (CheckInternetConnection() == false)
{
Dispatcher.Invoke(new Action(delegate
{
//internet access lost
}));
}
else
{
Dispatcher.Invoke(new Action(delegate
{
//internet access
}));
}

Thread.Sleep(2000);
}).Start();
    [DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
public static bool CheckInternetConnection()
{
int output = 0;
return InternetGetConnectedState(out output, 0);
}

这两个事件不是在所有场合都有效(只有当IP或网卡发生变化时)

NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged
NetworkChange.NetworkAddressChanged += NetworkChange_NetworkAddressChanged;

有人可以帮助我吗?

最佳答案

Note : In regaurds to your original solution

NetworkChange.NetworkAvailabilityChanged works fine, but there are a couple of caveats: 1) it doesn't tell you if you have Internet access, it just tells you whether there's at least one non-loopback network adapter working, and 2) there are often extra network adapters installed for various reasons that leave the system in a "network is available" state, even when your main Internet-connected adapter is disabled/unavailable - thanks to Peter Duniho

因为网络不仅仅是您的路由器或网卡,而且实际上是您随时尝试连接到的任何地方的每一跳。最简单和最可靠的方法就是 ping 一个众所周知的来源,例如谷歌,或者对您的一项互联网服务使用某种检测信号。

之所以这是唯一可靠的方法,是因为您和外界之间可能会出现任何数量的连接问题。即使是主要的服务提供商也可能倒闭。

因此,IMCP ping 到已知服务器(例如 Google)或在 WebClient 上调用 OpenRead 是两种有效的方法。这些调用相对来说并不昂贵,可以放入轻量级计时器或持续任务中。

至于您的评论,您可能会发出一个自定义事件信号,以表示在一定数量的安全失败后网络丢失

回答你的问题

But I fear that ping every 2 seconds consumes too many resources or can create some problems with internet connection.

这两种方法在 CPU 和网络流量方面都非常便宜,使用的任何资源都应该非常少

Note : Just make sure you are pinging or connecting to a server with high availability, this will allow such shenanigans and not just block you

Ping 示例

using System.Net.NetworkInformation;

// Implementation
using (var ping = new Ping())
{
var reply = ping.Send("www.google.com");
if (reply != null && reply.Status != IPStatus.Success)
{
// Raise an event
// you might want to check for consistent failures
// before signalling a the Internet is down
}
}

// Or if you wanted to get fancy ping multiple sources
private async Task<List<PingReply>> PingAsync(List<string> listOfIPs)
{
Ping pingSender = new Ping();
var tasks = listOfIPs.Select(ip => pingSender.SendPingAsync(ip, 2000));
var results = await Task.WhenAll(tasks);

return results.ToList();
}

连接示例

using System.Net; 

// Implementation
try
{
using (WebClient client = new WebClient())
{
using (client.OpenRead("http://www.google.com/"))
{
// success
}
}
}
catch
{
// Raise an event
// you might want to check for consistent failures
// before signalling the Internet is down
}

Note : Both these methods have an async variant that will return a Task and can be awaited for an Asynchronous programming pattern better suited for IO bound tasks

资源

Ping.Send Method

Ping.SendAsync Method

WebClient.OpenRead Method

WebClient.OpenReadAsync Method

关于C# 如何检测互联网连接/断开(带有事件)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48000031/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com