gpt4 book ai didi

c# - Webrequest 突然停止工作

转载 作者:行者123 更新时间:2023-11-30 21:22:29 27 4
gpt4 key购买 nike

HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(baseurl + url);
req.Timeout = 1000 * 10;
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream str = response.GetResponseStream();
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(str);
response.Close();
string imgurl = doc.DocumentNode.SelectSingleNode("//div[@class='one-page']/a/img[@class='manga-page']").Attributes["src"].Value;
req = (HttpWebRequest)HttpWebRequest.Create(imgurl);
req.Timeout = 1000 * 10;
response = (HttpWebResponse)req.GetResponse();
str = response.GetResponseStream();
Image img = Image.FromStream(str);
response.Close();
return img;

我在一个循环中运行这段代码(使用多个线程)来下载大约 4000 张图片,它在前数百张图片中表现出色,但随后(在我每次尝试的不同时间点)它突然停止工作,并且每次调用“req.GetResponse()”都会导致 TimeoutException。我不知道为什么会这样,也不知道可能出了什么问题或如何处理。任何帮助将不胜感激。

我用来运行此函数的代码(称为 GetPage(int) 并称为 c.GetPage(t))如下:

for (int j = 0; j < 2; j++)
{
BackgroundWorker bw = new BackgroundWorker();
num[bw] = j;
bgs.Add(bw);
bw.DoWork += (object sender, DoWorkEventArgs doargs) =>
{
int t = -1;
lock (lockObjForQueueOperations)
{
if (images.Count != 0)
t = images.Dequeue();
}
if(t < 0)
{
doargs.Result = false;
return;
}
currently[sender] = t;
Image img;
try { img = c.GetPage(t); }
catch (Exception e)
{
lock (lockObjForQueueOperations)
{
images.Enqueue(t);
}
lock (Console.Title)
{
if (num[sender] == 0) Console.ForegroundColor = ConsoleColor.Cyan;
else if (num[sender] == 1) Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("**ERR: Error fetshing page {0}, errormsg: {1}", t, e.Message);
Console.ForegroundColor = ConsoleColor.White;
}
doargs.Result = true;
Thread.Sleep(1000*2);
return;
}
lock (Console.Title)
{
if (num[sender] == 0) Console.ForegroundColor = ConsoleColor.Cyan;
else if (num[sender] == 1) Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\t\tLoaded page {0} of {1}.", t + 1, c.PagesCount);
Console.ForegroundColor = ConsoleColor.White;
}
string imgpath = Path.Combine(ndir, "Page " + (t + 1) + ".png");
img.Save(imgpath, System.Drawing.Imaging.ImageFormat.Png);
img.Dispose();
doargs.Result = true;
};
bw.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs runargs) =>
{
if ((bool)runargs.Result) bw.RunWorkerAsync();
else
{
finnishedworkers++;
if (finnishedworkers == 2) restetter.Set();
bw.Dispose();
}
};
bw.RunWorkerAsync();
}

最佳答案

HttpWebRequest 中的 Timeout 属性以毫秒为单位。目前将其设置为 10,000 仅需 10 秒,根据带宽和所提取数据的大小以及正在运行的代码的复杂性,这可能还不够。我说先尝试增加它。

关于c# - Webrequest 突然停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2292675/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com