因此,我的应用程序正在与服务器交换请求/响应(没有问题),直到互联网连接中断几秒钟,然后又恢复正常。然后是这样的代码:
response = (HttpWebResponse)request.GetResponse();
会引发一个异常,状态为ReceiveFailureConnectFailureKeepAliveFailure等。

现在,非常重要的一点是,如果Internet连接恢复,我能够继续与服务器通信,否则我将不得不从头开始,这将花费很长时间。

当互联网恢复正常时,您将如何恢复该通信?

目前,我一直在检查是否有可能与服务器通信,直到有可能为止(至少在理论上是这样)。我的代码尝试如下所示:

try
{
    response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
    // We have a problem receiving stuff from the server.
    // We'll keep on trying for a while
    if (ex.Status == WebExceptionStatus.ReceiveFailure ||
        ex.Status == WebExceptionStatus.ConnectFailure ||
        ex.Status == WebExceptionStatus.KeepAliveFailure)
    {
        bool stillNoInternet = true;

        // keep trying to talk to the server
        while (stillNoInternet)
        {
            try
            {
                response = (HttpWebResponse)request.GetResponse();
                stillNoInternet = false;
            }
            catch
            {
                stillNoInternet = true;
            }
        }
    }
}

但是,问题在于,即使Internet返回,第二个try-catch语句仍会引发异常。

我究竟做错了什么?还有另一种方法可以解决此问题吗?

谢谢!

最佳答案

您应该每次都重新创建请求,并且应该在每次重试之间都有等待的循环中执行重试。每次失败时,等待时间应逐渐增加。

例如。

ExecuteWithRetry (delegate {
    // retry the whole connection attempt each time
    HttpWebRequest request = ...;
    response = request.GetResponse();
    ...
});

private void ExecuteWithRetry (Action action) {
    // Use a maximum count, we don't want to loop forever
    // Alternativly, you could use a time based limit (eg, try for up to 30 minutes)
    const int maxRetries = 5;

    bool done = false;
    int attempts = 0;

    while (!done) {
        attempts++;
        try {
            action ();
            done = true;
        } catch (WebException ex) {
            if (!IsRetryable (ex)) {
                throw;
            }

            if (attempts >= maxRetries) {
                throw;
            }

            // Back-off and retry a bit later, don't just repeatedly hammer the connection
            Thread.Sleep (SleepTime (attempts));
        }
    }
}

private int SleepTime (int retryCount) {
    // I just made these times up, chose correct values depending on your needs.
    // Progressivly increase the wait time as the number of attempts increase.
    switch (retryCount) {
        case 0: return 0;
        case 1: return 1000;
        case 2: return 5000;
        case 3: return 10000;
        default: return 30000;
    }
}

private bool IsRetryable (WebException ex) {
    return
        ex.Status == WebExceptionStatus.ReceiveFailure ||
        ex.Status == WebExceptionStatus.ConnectFailure ||
        ex.Status == WebExceptionStatus.KeepAliveFailure;
}

关于c# - 互联网断开时继续尝试与服务器对话,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6956233/

10-10 13:52