基本上我的Windows服务应用程序中有一个阻塞集合,每次我想在集合中添加4个项目然后进行处理。
第一轮还可以,但第二轮失败了。 错误是
关于添加,BlockingCollection已标记为完成。
我的代码:
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");
它与我的old thread.
答案 0 :(得分:0)
根据TaW的提示,我在每次迭代中重新创建了集合。
每次迭代都有自己的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;
}