我有一個ConcurrentQueue和一個我需要獲取源代碼的URL列表。當以ConcurrentQueue對象作爲輸入參數使用Parallel.ForEach時,Pop方法不會工作(應該返回一個字符串)。ConcurrentQueue和Parallel.ForEach
我正在使用MaxDegreeOfParallelism並行設置爲四。我真的需要阻止併發線程的數量。是否使用並行冗餘的隊列?
在此先感謝。
// On the main class
var items = await engine.FetchPageWithNumberItems(result);
// Enqueue List of items
itemQueue.EnqueueList(items);
var crawl = Task.Run(() => { engine.CrawlItems(itemQueue); });
// On the Engine class
public void CrawlItems(ItemQueue itemQueue)
{
Parallel.ForEach(
itemQueue,
new ParallelOptions {MaxDegreeOfParallelism = 4},
item =>
{
var worker = new Worker();
// Pop doesn't return anything
worker.Url = itemQueue.Pop();
/* Some work */
});
}
// Item Queue
class ItemQueue : ConcurrentQueue<string>
{
private ConcurrentQueue<string> queue = new ConcurrentQueue<string>();
public string Pop()
{
string value = String.Empty;
if(this.queue.Count == 0)
throw new Exception();
this.queue.TryDequeue(out value);
return value;
}
public void Push(string item)
{
this.queue.Enqueue(item);
}
public void EnqueueList(List<string> list)
{
list.ForEach(this.queue.Enqueue);
}
}
分享你的進度... –
ItemQueue不應該都來自'ConcurrentQueue'幷包含'ConcurrentQueue',請選擇一個。 –
@Zroq:由於下載URL的源是一個I/O綁定操作,我必須聲明並行性是使用錯誤的工具。異步併發將使用更少的資源並且速度一樣快。 –