繁体   English   中英

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

[英]Multi-thread C# queue in .Net 4

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

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

使用任务并行库并使用使用线程池的默认调度程序。


好的,这是一次将 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();

    }

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

System.Collections.Concurrent.ConcurrentQueue<T>是否符合要求?

我会使用 System.Collections.Concurrent.ConcurrentQueue。

您可以安全地从多个线程中排队和出队。

查看 System.Collections.Concurrent.ConcurrentQueue。 如果需要等待,可以使用 System.Collections.Concurrent.BlockingCollection

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM