我有几个无限循环的任务(并行)。例如,1,2,3,4等
如何防止像{1这样的任务被连续添加到我的BlockingCollection<int>
?
我队列中的示例:
的
Task.Factory.StartNew(() =>
{
try
{
token.ThrowIfCancellationRequested();
while (true)
{
if (token.IsCancellationRequested)
token.ThrowIfCancellationRequested();
if (SomeCondition()) blockingCollection.Add(1);
Thread.Sleep(100);
}
}
catch (OperationCanceledException)
{
WriteLine("Cancel");
}
}, token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
答案 0 :(得分:0)
您是否尝试在添加之前检查是否已添加1?
编辑:更改了代码
int lastIndex = blockingCollection.Count - 1;
if (SomeCondition() && (lastIndex <= 0 || blockingCollection.ElementAt(lastIndex) != 1))
blockingCollection.Add(1);