Pregunta

I am trying to create a Windows Store App, that performs several avtivities that requires internet connectivity. My code handles a no internet connectivity by storing data in a temporary SQLite DB, but only when there is no internet connection. Something like this:

    // C#
    public bool isInternetConnected()
    {

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

Now, my problem is when I have a bad internet connection. My task will timeout, I will either have to handle the timeout or modify this method.

Does anybody has a good way to handle this????

¿Fue útil?

Solución

Try this: If the result is between 40 ~ 120, the latency is good, and your connection is good :)

Usage:

PingTimeAverage("stackoverflow.com", 4);

Implementation:

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;
}

Otros consejos

If you use a try statement with an exception it should be able to handle the operation when there is no internet connection. Not having the internet connection could be the exception.

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

I think using try-catch in this case is probably going to be the most efficient way to handle if internet breaks.

I'd try this and perhaps call it repeatedly and for multiple test URIs:

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;
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top