What is the best way to check for Internet connectivity using .NET?

后端 未结 27 2344
感动是毒
感动是毒 2020-11-22 07:41

What is the fastest and most efficient way to check for Internet connectivity in .NET?

27条回答
  •  耶瑟儿~
    2020-11-22 08:40

    I disagree with people who are stating: "What's the point in checking for connectivity before performing a task, as immediately after the check the connection may be lost". Surely there is a degree of uncertainty in many programming tasks we as developers undertake, but reducing the uncertainty to a level of acceptance is part of the challenge.

    I recently ran into this problem making an application which including a mapping feature which linked to an on-line tile server. This functionality was to be disabled where a lack of internet connectivity was noted.

    Some of the responses on this page were very good, but did however cause a lot of performance issues such as hanging, mainly in the case of the absence of connectivity.

    Here is the solution that I ended up using, with the help of some of these answers and my colleagues:

             // Insert this where check is required, in my case program start
             ThreadPool.QueueUserWorkItem(CheckInternetConnectivity);
        }
    
        void CheckInternetConnectivity(object state)
        {
            if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                using (WebClient webClient = new WebClient())
                {
                    webClient.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);
                    webClient.Proxy = null;
                    webClient.OpenReadCompleted += webClient_OpenReadCompleted;
                    webClient.OpenReadAsync(new Uri(""));
                }
            }
        }
    
        volatile bool internetAvailable = false; // boolean used elsewhere in code
    
        void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                internetAvailable = true;
                Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
                {
                    // UI changes made here
                }));
            }
        }
    

提交回复
热议问题