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