Awaiting ActionBlock<T> - TPL DataFlow
Asked Answered
S

1

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?

Salvador answered 8/9, 2013 at 16:38 Comment(0)
I
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.

Impeccant answered 8/9, 2013 at 16:45 Comment(1)
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: channel9.msdn.com/posts/TPL-Dataflow-Tour ... I'm a big fan btw, was a pleasure to have you answer my question :)Salvador

© 2022 - 2024 — McMap. All rights reserved.