日期:2014-05-17  浏览次数:20899 次

多线程 分批执行问题在线等待
本帖最后由 sky1314 于 2013-02-28 15:48:27 编辑
我写了一个有网页数据抓取程序,大约要访问100多W个页面.想用多线程来执行,提高效率.最多只有10个正在执行的线程.我对多线程用的不怎么熟悉.
写了一个for 循环 
Thread thread = new Thread(new ParameterizedThreadStart(dod));
thread.Start(ts);

会不停的开启线程,3,4百了.结果一开就被封IP了.悲剧.

------解决方案--------------------
 foreach (string targetUrl in targetUrls)
这里面有多少个URL?太多了不行吧。
你限量呗。
object obj = new object();
List<string> targetUrls;

for(int i = 0;i<10;i++)
{
 TimerExampleState ts = new TimerExampleState();
                    ts.BaseUrl = baseUrl;
                    ts.Stem = item;
                    ts.TargetUrl = targetUrl;
                    ts.Curi = uri;
                    Thread thread = new Thread(dod);
                    thread.Start();

}

在线程里去取url处理
每次取lock(obj){
// 从list里取出url处理
}
这样就限制了线程的数量了。
------解决方案--------------------
 foreach (string targetUrl in targetUrls)
 {
                    TimerExampleState ts = new TimerExampleState();
                    ts.BaseUrl = baseUrl;
                    ts.Stem = item;
                    ts.TargetUrl = targetUrl;
                    ts.Curi = uri;
                    Thread thread = new Thread(new ParameterizedThreadStart(dod));
                    thread.Start(ts);
}

这个线程创建太多了。


for(int i=0;i<10;i++)
{
ThreadPool.QueueUserWorkItem(dod);
}

public  void dod()
{

  foreach (string targetUrl in targetUrls)
  {
                    TimerExampleState ts = new TimerExampleState();
                    ts.BaseUrl = baseUrl;
                    ts.Stem&nb