有没有更好的方法来检查Internet连接? [英] Is There A Better Way to Check Internet Connectivity?

查看:102
本文介绍了有没有更好的方法来检查Internet连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好

问题:有没有更好的方法来检查内部连接?

Question:  Is there a better way to check for internect connectivity?

背景:
我正在开发一个应用程序,我想在后台检查用户计算机上的Internet连接,并在连接断开时打开错误页面.我正在使用以下代码,但工作正常,但是,我注意到 当互联网连接断开并且正在评估ELSE语句时,该程序将无响应.还有另一种测试互联网连接性的方法吗?

Background:
I'm working on an application which I want to check for internet connectivity on the user's computer in the background and open up an error page when the connectivity is lost.  I'm using the following code and it's working fine, however, I noticed that when internet connectivity was lost and the ELSE statement was being evaluated, the program becomes unresponsive.  Is there another way to test for internet connectivity?

如果不是,那么从WINDOW_LOADED事件检查连接是否可能不是一个好主意.这提出了另一个问题,我将在另一篇文章中解决.

If not, then perhaps it may not be a good idea to check for connectivity from the WINDOW_LOADED event.  This brings up another question that I'll address in another post.

这是我的代码:


Imports System.Net

Public Class CheckInetConnection
    Public Shared Function CheckForInternetConnection() As Boolean
        Try
            Using client = New WebClient()
                Using stream = client.OpenRead("http://www.google.com")
                    Return True
                End Using
            End Using
        Catch
            Return False
        End Try
    End Function
End Class

推荐答案

您可以使用InternetGetConnectedState

You can use InternetGetConnectedState

http://stackoverflow.com/Questions/843810/c-sharp-最快的测试互联网连接方式

您也可以尝试Ping课

You can also try Ping class

public bool PingNetwork(string hostNameOrAddress)
    {
        bool pingStatus = false;
 
        using (Ping p = new Ping())
        {
            string data = "test";
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            int timeout = 120;
 
            try
            {
                PingReply reply = p.Send(hostNameOrAddress, timeout, buffer);
                pingStatus = (reply.Status == IPStatus.Success);
            }
            catch (Exception)
            {
                pingStatus = false;
            }
        }
 
        return pingStatus;
    }

 


这篇关于有没有更好的方法来检查Internet连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆