What is the fastest and most efficient way to check for Internet connectivity in .NET?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
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:
Instead of checking, just perform the action (web request, mail, ftp, etc.) and be prepared for the request to fail, which you have to do anyway, even if your check was successful.
Consider the following:
If the network is down your action will fail just as rapidly as a ping, etc.
Multi threaded version of ping:
Use NetworkMonitor to monitoring network state and internet connection.
Sample:
For my application we also test by download tiny file.
Also. Some ISP may use middle server to cache file. Add random unused parameter eg. https://www.microsoft.com/favicon.ico?req=random_number Can prevent caching.