本人本人做了一个网站图片的抓取, 感觉速度有点慢抓取4000张图片 可能得用15分钟左右的时间,
本人百度看 用线程可以加快抓取,然后创建了5个线程抓取,但是 5个线程是同步执行 同样的操作 一个图片就抓取了5次,
代码应该怎么写 才能让线程 不抓取同样的内容呢
本人百度看 用线程可以加快抓取,然后创建了5个线程抓取,但是 5个线程是同步执行 同样的操作 一个图片就抓取了5次,
代码应该怎么写 才能让线程 不抓取同样的内容呢
解决方案
5
页号(序数)应作为参数传入,而不是在 uploadimg 中循环产生
也就是 uploadimg 方法每次抓取一个页面中的图片
也就是 uploadimg 方法每次抓取一个页面中的图片
5
分批次。
多线程编程,关键在于分派任务。
可以使用一个队列存储url,每次线程从队列中获取一批url(加锁,或使用线程安全的队列)。
多线程编程,关键在于分派任务。
可以使用一个队列存储url,每次线程从队列中获取一批url(加锁,或使用线程安全的队列)。
5
给你个控制台演示代码你体会一下
static void Main(string[] args)
{
var tasks = Enumerable.Range(0, 50);
var q = from x in tasks.AsParallel().WithDegreeOfParallelism(5)
select DoIt(x);
Console.WriteLine("总共用了{0}个线程执行了{1}个任务!\n", q.Distinct().Count(), tasks.Count());
}
static int DoIt(int n)
{
var tid = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("{0} : {1}", tid, n);
return tid;
}
5
private Queue<string> m_que_url = new Queue<string>();
private void DownLoadCallBack() {
string strUrl = string.Empty;
WebClient web = new WebClient();
while (true) {
lock (m_que_url) {
if (m_que_url.Count == 0) break;
strUrl = m_que_url.Dequeue();
}
try {
web.DownloadFile(strUrl, "yourfilename");
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
}
//set m_que_url
int nThreadCount = 50;
for (int i = 0; i < nThreadCount; i++) {
new Thread(DownLoadCallBack) { IsBackground = true }.Start();
}