无法在第二轮中将项目添加到集合中 [英] Can't add items to the collection in the second round
问题描述
基本上,我的Windows服务应用程序中有一个blockcollection集合,每次我想向集合中添加4个项目然后对其进行处理。
Basically I have a blockingcollection in my windows service application, each time I want to add 4 items to the collection then processing it.
第一轮没问题,但是第二轮失败了。
错误是
The first round is okay, but the second round failed. The error is
关于添加的内容,BlockingCollection已标记为完整。
The BlockingCollection has been marked as complete with regards to additions.
我的代码:
public static BlockingCollection<Tuple<ChannelResource, string>> bc = new BlockingCollection<Tuple<ChannelResource, string>>();
public static List<string> list = new List<string>(); // then add 100 items to it.
主要应用代码:
ProcessCall pc = new ProcessCall(OvrTelephonyServer, bc);
while (true)
{
ThreadEvent.WaitOne(waitingTime, false);
lock (SyncVar)
{
Console.WriteLine("Block begin");
for (int i = 0; i < 4; i++)
{
var firstItem = list.FirstOrDefault();
ChannelResource cr = OvrTelephonyServer.GetChannel();
bc.TryAdd(Tuple.Create(cr, firstItem));
list.Remove(firstItem);
}
bc.CompleteAdding();
pc.SimultaneousCall();
Console.WriteLine("Blocking end");
if (ThreadState != State.Running) break;
}
}
我意识到有一个代码 bc.CompleteAdding();
阻止进一步的添加。所以我将其注释掉,但不会进入第二轮。它没有达到代码 Console.WriteLine( Blocking end);
与我的旧线程。
I realized that there was a code bc.CompleteAdding();
to block the further additions. So I commented out it, but it would not go to the second round block. It didn't reach the code Console.WriteLine("Blocking end");
It was same as my old thread.
推荐答案
根据提示来自TaW,我在每次迭代中都重新创建了集合。
By the hint from TaW, I recreated the collection in each iteration.
每个迭代都有自己的 CompleteAdding()
。
lock (SyncVar)
{
bc = new BlockingCollection<Tuple<ChannelResource, string>>();
ProcessCall pc = new ProcessCall(OvrTelephonyServer, bc);
if (list.Count > 0)
{
Console.WriteLine("Block begin");
for (int i = 0; i < 4; i++)
{
if (list.Count > 0)
{
var firstItem = list.FirstOrDefault();
ChannelResource cr = OvrTelephonyServer.GetChannel();
bc.TryAdd(Tuple.Create(cr, firstItem));
list.Remove(firstItem);
}
}
bc.CompleteAdding();
pc.SimultaneousCall();
Console.WriteLine("Blocking end");
}
if (ThreadState != State.Running) break;
}
这篇关于无法在第二轮中将项目添加到集合中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!