繁体   English   中英

如何验证C#中是否存在良好的互联网连接?

[英]How to verify is there is a good internet connection in C#?

我正在尝试创建一个Windows应用商店应用程序,它执行几个需要互联网连接的活动。 我的代码通过在临时SQLite数据库中存储数据来处理无互联网连接,但仅在没有互联网连接的情况下。 像这样的东西:

    // C#
    public bool isInternetConnected()
    {

        ConnectionProfile conn = NetworkInformation.GetInternetConnectionProfile();
        bool isInternet = conn != null && conn.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess;
        return isInternet;
    }

现在,我的问题是当我的互联网连接不良时。 我的任务将超时,我将要么处理超时或修改此方法。

有没有人有办法处理这个????

试试这个:如果结果在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;
}

如果您使用带有异常的try语句,它应该能够在没有Internet连接时处理该操作。 没有互联网连接可能是例外。

try 
{
    // Do not initialize this variable here.
}
catch
{
}

我认为在这种情况下使用try-catch可能是处理互联网中断时最有效的方法。

我试试这个并且可能反复调用它并用于多个测试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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM