我正在尝试下载包含大量域名的文本文件:
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
// backgroundworker
string action = e.Argument as string;
if (action == "xc_download")
{
// this downloads the daily domains from the main site
// format the date to append to the url
DateTime theDate = DateTime.Now;
theDate.ToString("yyyy-MM-dd");
string downloadURL = String.Empty;
downloadURL = ("http://www.namejet.com/Download/" + (theDate.ToString("M-dd-yyyy") + ".txt"));
using (WebClient wc = new WebClient())
{
string urls = wc.DownloadString(downloadURL);
dgView.Rows.Add(urls);
}
} // if (action == "xc_download")
}
下载后,我正在尝试将它们添加到数据网格中。问题是,这非常非常缓慢。是否有更快的方式来下载文本文件并将数据添加到我应该使用的gridview中?
答案 0 :(得分:0)
您可以并行化下载过程。一个选项是TPL' Parallel.ForEach
。您可以设置最大并发操作数(下载)以防止服务器被泛洪。
List<string> downloads = new List<string>();
downloads.Add(...);
Parallel.ForEach
( downloads
, new ParallelOptions() { MaxDegreeOfParallelism = 8 } /* max 8 downloads simultaneously */
, url => Download(url)
);
然后创建一个下载方法并在那里处理下载:
private void Download(string url)
{
// download
this.Invoke((MethodInvoker)delegate()
{
// update the UI inside here
});
}