【问题标题】:How to verify is there is a good internet connection in C#?如何验证 C# 中是否有良好的互联网连接?
【发布时间】:2014-04-02 04:23:07
【问题描述】:
我正在尝试创建一个 Windows 应用商店应用程序,该应用程序执行需要互联网连接的多项活动。
我的代码通过将数据存储在临时 SQLite DB 中来处理无 Internet 连接,但仅在没有 Internet 连接时。像这样的:
// C#
public bool isInternetConnected()
{
ConnectionProfile conn = NetworkInformation.GetInternetConnectionProfile();
bool isInternet = conn != null && conn.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess;
return isInternet;
}
现在,我的问题是当我的互联网连接不好时。我的任务将超时,我将不得不处理超时或修改此方法。
有没有人有好的方法来处理这个????
【问题讨论】:
标签:
c#
windows-runtime
windows-store-apps
internet-connection
【解决方案1】:
试试这个:
如果结果在 40 ~ 120 之间,则延迟很好,您的连接也很好:)
用法:
PingTimeAverage("stackoverflow.com", 4);
实施:
public static double PingTimeAverage(string host, int echoNum)
{
long totalTime = 0;
int timeout = 120;
Ping pingSender = new Ping ();
for (int i = 0; i < echoNum; i++)
{
PingReply reply = pingSender.Send (host, timeout);
if (reply.Status == IPStatus.Success)
{
totalTime += reply.RoundtripTime;
}
}
return totalTime / echoNum;
}
【解决方案2】:
如果您使用带有异常的 try 语句,它应该能够在没有 Internet 连接时处理该操作。没有互联网连接可能是个例外。
try
{
// Do not initialize this variable here.
}
catch
{
}
我认为在这种情况下使用 try-catch 可能是处理网络中断时最有效的方法。
【解决方案3】:
我会尝试这个,也许会重复调用它并用于多个测试 URI:
public static async Task<bool> CheckIfWebConnectionIsGoodAsync(TimeSpan? minResponseTime, Uri testUri)
{
if (minResponseTime == null)
{
minResponseTime = TimeSpan.FromSeconds(0.3);
}
if (testUri == null)
{
testUri = new Uri("http://www.google.com");
}
var client = new HttpClient();
var cts = new CancellationTokenSource(minResponseTime.Value);
try
{
var task = client.GetAsync(testUri).AsTask(cts.Token);
await task;
if (task.IsCanceled)
return false;
return true;
}
catch (Exception)
{
return false;
}
}