我正在获取html源代码并解析它。之后,我想下载图像。我下载它们。但有时候不下载。因为我不能使用我需要的线程或并行编程,我不知道。我的来源是:
foreach(var pic in pics)
{
try {
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadFileAsync(new Uri(pic.Attributes[cmbAttr.Text].Value), folder + "\\" + picid.ToString() + ".jpg");
System.Threading.Thread.Sleep(1500); // I wrote sleep code, because i dont know parallel programming. But sometimes it is not downloading in 1500 milisecond.
picid++;
}catch(Exception err)
{
label8.Text=(err.Message.ToString());
continue;
}
}
这是我的代码。我想按顺序下载图片。 1.jpg,2.jpg等我也下载了它。但有时它会出错。因为另一个下载开始,而上次下载之前完成。我想在完成上次下载后开始。我的英语不好。我希望我说的是真的。 感谢帮助。
答案 0 :(得分:0)
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
foreach(var pic in pics)
{
Task.Factory.StartNew(Object state =>
{
var data = (dynamic)state;
Int32 id = (Int32)state.Id;
Picture picture = (Picture)state.Picture;
client.DownloadFile(new Uri(picture.Attributes[cmbAttr.Text].Value), folder + "\\" + id.ToString() + ".jpg")
}, new { Id = picid, Picture = pic });
++picid;
}