C# C TPL数据流批处理块等待完成永不返回
我创建了一个小测试程序来说明我的问题C# C TPL数据流批处理块等待完成永不返回,c#,tpl-dataflow,C#,Tpl Dataflow,我创建了一个小测试程序来说明我的问题 class Item { public string Name; } class Program { static BatchBlock<Item> items = new BatchBlock<Item>(2); static ConcurrentBag<Item> bag = new ConcurrentBag<Item>(); public static async T
class Item
{
public string Name;
}
class Program
{
static BatchBlock<Item> items = new BatchBlock<Item>(2);
static ConcurrentBag<Item> bag = new ConcurrentBag<Item>();
public static async Task Main(string[] args)
{
var insertItems = new ActionBlock<Item[]>(b => BatchProcessor(b));
items.LinkTo(insertItems);
var finished = items.Completion.ContinueWith(delegate { insertItems.Complete(); }).ConfigureAwait(false);
Console.WriteLine("From main 1");
items.Post(new Item() { Name = "1" });
Console.WriteLine("From main 2");
items.Post(new Item() { Name = "2" });
Console.WriteLine("From main 3");
items.Post(new Item() { Name = "3" });
Console.WriteLine("From main 4");
items.Post(new Item() { Name = "4" });
Console.WriteLine("From main 5");
items.Post(new Item() { Name = "5" });
Console.WriteLine("From main 6");
items.Post(new Item() { Name = "6" });
Console.WriteLine("From main 7");
items.Post(new Item() { Name = "7" });
Console.WriteLine("Finishing");
items.TriggerBatch();
await items.Completion; // Never completes!!!
}
static void BatchProcessor(Item[] items)
{
Console.WriteLine("Callback");
foreach(var i in items)
{
Console.WriteLine("From Callback " + i.Name);
bag.Add(i);
}
}
}
我遗漏了什么?向块发送数据后,需要调用
Complete
这:
为了等待整个流程的完成,应该:
items.Complete()
await insertItems.Completion;
最后,您可以将块链接到传播完成,这样在这种情况下就不需要使用ContinueWith
这:
可替换为:
items.LinkTo(insertItems, new DataflowLinkOptions() { PropagateCompletion = true });
完成向块发送数据后,需要调用
Complete
这:
为了等待整个流程的完成,应该:
items.Complete()
await insertItems.Completion;
最后,您可以将块链接到传播完成,这样在这种情况下就不需要使用ContinueWith
这:
可替换为:
items.LinkTo(insertItems, new DataflowLinkOptions() { PropagateCompletion = true });
我相信
items.Completion.ContinueWith(委托{insertItems.Complete();})
是蛇在吃自己的尾巴,批处理只会完成一次Completion
被解析,而这只会在调用Complete()
时被解析。我相信items.Completion.ContinueWith(委托{insertItems.Complete();})
如果蛇吃自己的尾巴,则批处理只会完成一次完成
已解决,而只有在调用complete()
时才会解决该问题。
items.LinkTo(insertItems, new DataflowLinkOptions() { PropagateCompletion = true });