首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >.Net 4中的多线程C#队列

.Net 4中的多线程C#队列
EN

Stack Overflow用户
提问于 2012-04-10 18:44:03
回答 5查看 2.4K关注 0票数 1

我正在开发一个简单的网页爬虫。我搜索并找到了很多实现多线程爬虫的解决方案。创建线程安全队列以包含唯一URL的最佳方法是什么?

编辑:.Net 4.5中有没有更好的解决方案?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2012-04-10 18:45:52

使用Task Parallel Library并使用使用ThreadPool的默认计划程序。

好的,这是一个最小的实现,它一次排队30个URL:

代码语言:javascript
运行
复制
    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);
            }
        }
    }

虚拟用法:

代码语言:javascript
运行
复制
    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();

    }
票数 2
EN

Stack Overflow用户

发布于 2012-04-10 19:21:53

ConcurrentQueue确实是框架的线程安全队列实现。但由于您可能会在producer-consumer场景中使用它,所以您真正想要的类可能是无限有用的BlockingCollection

票数 2
EN

Stack Overflow用户

发布于 2012-04-10 18:51:41

System.Collections.Concurrent.ConcurrentQueue<T>能满足你的要求吗?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10087248

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档