[英]Awaiting ActionBlock<T> - TPL DataFlow
I am using TPL DataFlow and an ActionBlock to create parallelism. 我正在使用TPL DataFlow和ActionBlock来创建并行性。 The reason for using TPL DataFlow is because it supports asynchronicity, except I can't get it to work.
使用TPL DataFlow的原因是因为它支持异步性,除非我无法使其工作。
var ab = new ActionBlock<Group>(async group =>
{
try {
labelStatus.Text = "Getting admins from " + group.Gid;
await GetAdminsFromGroup(group.Gid);
}catch (ArgumentOutOfRangeException ex) {
// Log exception
}
}, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 10 });
db.Groups.ToList().ForEach(i => ab.Post(i));
ab.Complete();
MessageBox.Show("Complete");
The message box is displaying almost instantly, although the ActionBlocks still run. 虽然ActionBlocks仍在运行,但消息框几乎立即显示。 How can I
await
until the ActionBlock is complete? 在ActionBlock完成之前我该如何
await
?
ActionBlock<T>
exposes a Completion
property. ActionBlock<T>
公开Completion
属性。 That's a Task
which completes when the block has finished processing everything. 这是一个
Task
,当块完成所有处理后完成。 So you can await that: 所以你可以等待:
ab.Complete();
await ab.Completion;
MessageBox.Show("Complete");
I must admit I haven't used TPL Dataflow myself, but the examples suggest that should be okay. 我必须承认我自己没有使用过TPL Dataflow,但是这些例子表明应该没问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.