我正在开发一个简单的网页爬虫。我搜索并找到了很多实现多线程爬虫的解决方案。创建线程安全队列以包含唯一URL的最佳方法是什么?
编辑:.Net 4.5中有没有更好的解决方案?
发布于 2012-04-10 18:45:52
使用Task Parallel Library并使用使用ThreadPool的默认计划程序。
好的,这是一个最小的实现,它一次排队30个URL:
public static void WebCrawl(Func<string> getNextUrlToCrawl, // returns a URL or null if no more URLs
Action<string> crawlUrl, // action to crawl the URL
int pauseInMilli // if all threads engaged, waits for n milliseconds
)
{
const int maxQueueLength = 50;
string currentUrl = null;
int queueLength = 0;
while ((currentUrl = getNextUrlToCrawl()) != null)
{
string temp = currentUrl;
if (queueLength < maxQueueLength)
{
Task.Factory.StartNew(() =>
{
Interlocked.Increment(ref queueLength);
crawlUrl(temp);
}
).ContinueWith((t) =>
{
if(t.IsFaulted)
Console.WriteLine(t.Exception.ToString());
else
Console.WriteLine("Successfully done!");
Interlocked.Decrement(ref queueLength);
}
);
}
else
{
Thread.Sleep(pauseInMilli);
}
}
}
虚拟用法:
static void Main(string[] args)
{
Random r = new Random();
int i = 0;
WebCrawl(() => (i = r.Next()) % 100 == 0 ? null : ("Some URL: " + i.ToString()),
(url) => Console.WriteLine(url),
500);
Console.Read();
}
发布于 2012-04-10 19:21:53
ConcurrentQueue确实是框架的线程安全队列实现。但由于您可能会在producer-consumer场景中使用它,所以您真正想要的类可能是无限有用的BlockingCollection。
发布于 2012-04-10 18:51:41
System.Collections.Concurrent.ConcurrentQueue<T>
能满足你的要求吗?
https://stackoverflow.com/questions/10087248
复制相似问题