使用 .NET 检查 Internet 连接的任何新方法?
Any new method on checking internet connectivity using .NET?
我已经阅读了这里 post 提出的一些问题,我发现这个 post 是关于这个问题最可靠的:What is the best way to check for Internet connectivity using .NET?
但是如果接口连接的网络google被阻塞了怎么办? (例如中国的互联网)
如果您正在检查 Internet 连接,您可能有一个原因...这意味着您正在寻找使用某些特定的 Web 资源。 因此检查该资源。
更好的是,根本不要检查。 Internet 服务随时可能启动或关闭...包括您 运行 之间的那一刻您的支票以及您何时尝试使用该服务。这意味着您所做的任何事情都必须能够处理失败。所以不要 运行 支票;将工作放入您的异常处理程序中。
我知道使用异常处理进行流控制听起来可能很慢或很奇怪。但不使用异常进行流量控制的主要原因是它几乎是所有计算机科学中你能做的最慢的事情。你知道更糟糕的是什么吗?等待网络数据包绕了半个地球或者超时,就是这样。
在极少数情况下,当您只想向用户显示一般互联网状态时,您可以使用 same way Microsoft does 并使用 www.msftncsi.com
.
如果你想要检查.Net
中的互联网状态而不依赖于WebClient
class或Google
,这是最好的方法
First, import the DLL wininet
[System.Runtime.InteropServices.DllImport("wininet.dll")]
然后,调用 static extern bool InternetGetConnectedState(...)
这 returns true
如果互联网连接, false
如果无法连接,不管 Google
:
[System.Runtime.InteropServices.DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
public static bool IsConnected()
{
return InternetGetConnectedState(out int description, 0);
}
其中:
if(IsConnected())
{
//Internet is connected
}
else
{
//Internet is not connected
}
我已经阅读了这里 post 提出的一些问题,我发现这个 post 是关于这个问题最可靠的:What is the best way to check for Internet connectivity using .NET?
但是如果接口连接的网络google被阻塞了怎么办? (例如中国的互联网)
如果您正在检查 Internet 连接,您可能有一个原因...这意味着您正在寻找使用某些特定的 Web 资源。 因此检查该资源。
更好的是,根本不要检查。 Internet 服务随时可能启动或关闭...包括您 运行 之间的那一刻您的支票以及您何时尝试使用该服务。这意味着您所做的任何事情都必须能够处理失败。所以不要 运行 支票;将工作放入您的异常处理程序中。
我知道使用异常处理进行流控制听起来可能很慢或很奇怪。但不使用异常进行流量控制的主要原因是它几乎是所有计算机科学中你能做的最慢的事情。你知道更糟糕的是什么吗?等待网络数据包绕了半个地球或者超时,就是这样。
在极少数情况下,当您只想向用户显示一般互联网状态时,您可以使用 same way Microsoft does 并使用 www.msftncsi.com
.
如果你想要检查.Net
中的互联网状态而不依赖于WebClient
class或Google
,这是最好的方法
First, import the DLL wininet
[System.Runtime.InteropServices.DllImport("wininet.dll")]
然后,调用 static extern bool InternetGetConnectedState(...)
这 returns true
如果互联网连接, false
如果无法连接,不管 Google
:
[System.Runtime.InteropServices.DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
public static bool IsConnected()
{
return InternetGetConnectedState(out int description, 0);
}
其中:
if(IsConnected())
{
//Internet is connected
}
else
{
//Internet is not connected
}