簡體   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