我有一个包含URL列表的ConcurrentQueue,我需要获取它们的源代码。当使用Parallel.ForEach和ConcurrentQueue对象作为输入参数时,Pop方法无法正常工作(应返回字符串)。
我正在使用设置了最大并行度为4的Parallel。我真的需要限制并发线程数。使用队列和并行处理是否多余?
提前感谢您的帮助。
我正在使用设置了最大并行度为4的Parallel。我真的需要限制并发线程数。使用队列和并行处理是否多余?
提前感谢您的帮助。
// 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);
}
}
ConcurrentQueue
也包含一个ConcurrentQueue
,请选其一。 - Scott ChamberlainSemaphoreSlim
来实现async
。 - Stephen Cleary