try
{
ParallelOptions Options = new ParallelOptions();
Options.CancellationToken = base.DownloadCancellation.Token;
Parallel.ForEach(base.BlockingCollection1, Options, ActiveSeeder =>
{
//...
});
}
catch
{
if (base.DownloadCancellation.IsCancellationRequested)
return false;
}
Parallel.Foreach/For 调用 BlockingCollection1.Take 函数时是否使用我放入 ParallelOptions 的 CancellationToken?
有机会知道吗?
请您参考如下方法:
Parallel.ForEach() 不调用Take()完全没有,所以你的问题是无效的。
相反,它将像对待任何其他集合一样对待集合 IEnumerable<T> ,这意味着它将调用其 GetEnumerator()然后处理结果。 What GetEnumerator() does for BlockingCollection is documented :
Unlike
GetConsumingEnumerable,BlockingCollection<T>.IEnumerable<T>.GetEnumeratorreturns a standard enumerator that does not modify the underlying collection. If other threads are adding or removing elements concurrently whenGetEnumeratoris called, then the elements returned by the enumerator might not represent the current state of the collection.
如果您想在迭代时从集合中删除项目,您可以使用 GetConsumingEnumerable() ,它确实有 an overload that takes CancellationToken .但这实际上不会很好地工作,所以最好使用 GetConsumingPartitioner() from ParallelExtensionsExtras (code on GitHub)。
