7

I am using TPL DataFlow and an ActionBlock to create parallelism. The reason for using TPL DataFlow is because it supports asynchronicity, except I can't get it to work.

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. How can I await until the ActionBlock is complete?

James Jeffery
  • 12,093
  • 19
  • 74
  • 108

1 Answers1

19

ActionBlock<T> exposes a Completion property. That's a Task which completes when the block has finished processing everything. 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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 2
    Excellent Jon, that worked. I was just watching a video on Channel 9 that also mentions the Completion property. For anyone interested it's here: http://channel9.msdn.com/posts/TPL-Dataflow-Tour ... I'm a big fan btw, was a pleasure to have you answer my question :) – James Jeffery Sep 08 '13 at 16:54