连接在长时间运行后意外关闭 C#

did*_*edi 5 c# webclient system.net.webexception

嗨,我正在为一个网站制作一个爬虫。经过大约 3 小时的爬网,我的应用程序因 WebException 停止。下面是我在 C# 中的代码。client 是预定义的WebClient对象,每次 gameDoc 已经被处理时都会被处理。gameDoc 是一个HtmlDocument对象(来自HtmlAgilityPack

while (retrygamedoc)
{
    try
    {
        gameDoc.LoadHtml(client.DownloadString(url)); // this line caused the exception
        retrygamedoc = false;
    }
    catch
    {
        client.Dispose();
        client = new WebClient();

        retrygamedoc = true;
        Thread.Sleep(500);
    }
}
Run Code Online (Sandbox Code Playgroud)

我试图从这个答案中使用下面的代码(以保持网络客户端新鲜)

while (retrygamedoc)
{
    try
    {
        using (WebClient client2 = new WebClient())
        {
            gameDoc.LoadHtml(client2.DownloadString(url)); // this line cause the exception
            retrygamedoc = false;
        }
    }
    catch
    {
        retrygamedoc = true;
        Thread.Sleep(500);
    }
}
Run Code Online (Sandbox Code Playgroud)

但结果还是一样。然后我使用 StreamReader 并且结果保持不变!下面是我使用 StreamReader 的代码。

while (retrygamedoc)
{
    try
    {
        // using native to check the result
        HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(url);
        string responsestring = string.Empty;
        HttpWebResponse response = (HttpWebResponse)webreq.GetResponse(); // this cause the exception
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            responsestring = reader.ReadToEnd();
        }
        gameDoc.LoadHtml(client.DownloadString(url));

        retrygamedoc = false;
    }
    catch
    {
        retrygamedoc = true;
        Thread.Sleep(500);
    }
}
Run Code Online (Sandbox Code Playgroud)

我应该怎么做和检查?我很困惑,因为我能够在同一个站点上的某些页面上爬行,然后在大约 1000 次结果中,它导致了异常。来自异常的消息是 onlyThe request was aborted: The connection was closed unexpectedly.并且状态是ConnectionClosed

附注。该应用程序是桌面表单应用程序。

更新 :

现在我正在跳过这些值并将它们变成 null 以便爬行可以继续。但是如果真的需要数据,我还是得手动更新爬取结果,很累,因为结果有几千条记录。请帮我。

例子 :

就像你从网站上下载了大约 1300 条数据,然后应用程序停止说,The request was aborted: The connection was closed unexpectedly.而你的所有互联网连接仍然打开并且速度很好。

Jac*_*cob 4

ConnectionClosed可能表明(并且可能确实如此)您正在下载的服务器正在关闭连接。也许它注意到您的客户提出了大量请求,并拒绝您提供额外的服务。

由于您无法控制服务器端的恶作剧,我建议您使用某种逻辑稍后重试下载。