我正在使用BlockingCollection
生产者消费者模式,我得到了一个例外,我想在上面写一个专利——谷歌只有两个结果!期望是“CompleteAdding 不能与添加到集合中同时使用”,它发生在 iTryAdd
在 BlockingCollection 上,如下所示:
public void EnqueueTask(T item)
{
if (!_cancellationTokenSource.IsCancellationRequested)
{
_workerQueue.Add(item);
}
}
在CompleteAdding
Consumer-Producer 包装类的处置中调用:
public void Dispose()
{
if (!_IsActive)
return;
_IsActive = false;
_cancellationTokenSource.Cancel();
_workerQueue.CompleteAdding();
// Wait for the consumer's thread to finish.
for (int i = 0; i < _workers.Length; ++i)
{
Task t1 = Task.Factory.StartNew(() =>
{
try
{
if (!_workers[i].Join(4000))
LogWriter.Trace("Failed to join thread", "ThreadFailureOnDispose");
}
catch (Exception ex)
{
OnLogged(ex.Message + ex.StackTrace);
}
});
}
// Release any OS resources.
}
微软的人有想法吗?我应该在取消之后和调用 CompleteAdding 之前睡觉吗?