一次成功测试后,InternetCheckConnection将返回true

时间:2012-09-21 23:14:03

标签: wpf connection return network-monitoring

平台: WPF(.NET 4.5)

为了尽可能快地检查互联网连接,我使用此功能:

    [DllImport("wininet.dll")]
    public extern static bool InternetCheckConnection(string lpszUrl, int dwFlags, int dwReserved);

问题在于,如果我已连接到互联网并且我的程序正在执行InternetCheckConnection,则会返回 true (如预期的那样) BUT 我把程序睡了一会儿,在这一刻我将电脑与互联网断开连接,之后再次检查连接,我还是 true

为什么?!

我准备了代码来解决问题:

using System;
using System.Runtime.InteropServices;
using System.Threading;

namespace InternetCheckConnectionTest
{
    class Program
    {
        [DllImport("wininet.dll")]
        public extern static bool InternetCheckConnection(string lpszUrl, int dwFlags, int dwReserved);

        static void Main(string[] args)
        {
            string www = "http://www.google.com/";

            Console.WriteLine("Checking connection...");
            bool connected = InternetCheckConnection(www, 1, 0);

            Console.WriteLine("Connection check returned " + connected.ToString());

            TimeSpan ts = new TimeSpan(0, 0, 20);
            Console.WriteLine("\nYou have " + ts.TotalSeconds.ToString() + " seconds to (dis)connect from/to the Internet.\n");
            Thread.Sleep(ts);

            Console.WriteLine("Checking connection once again...");
            connected = InternetCheckConnection(www, 1, 0);
            Console.WriteLine("Connection (2nd) check returned " + connected.ToString());
        }
    }
}

在开始此程序之前,请确保已连接到Internet。
在此消息之后:

  

您有20秒钟(不)连接到互联网。

断开互联网连接。即使您与互联网断开连接,您也会看到InternetCheckConnection(www, 1, 0)返回 True 。问题是为什么

0 个答案:

没有答案