Reputation: 1897
I have the following small test method to play with ActionBlock. It writes out the trace messages in the expected order, but it never completes. The test method never exits.
What am I doing wrong here? Thx in advance.
[TestMethod]
public async Task ActionBlockTest()
{
var rnd = new Random(DateTime.Now.Millisecond);
var delay = new ActionBlock<int>(item =>
{
var start = DateTime.Now;
Trace.WriteLine(string.Format("{0:ss fff} item start processing ({1})", start, item));
return Task.Delay(item).ContinueWith(t => Trace.WriteLine(string.Format("{0:ss fff} item finished processing ({1}) took {2} ms", DateTime.Now, item, (DateTime.Now - start).TotalMilliseconds)));
}, new ExecutionDataflowBlockOptions
{
BoundedCapacity = 4,
MaxDegreeOfParallelism = 2
});
for(int i = 0; i < 8; i++)
{
var d = rnd.Next(100, 1000);
Trace.WriteLine(string.Format("{0:ss fff} posting {1}", DateTime.Now, d));
await delay.SendAsync(d);
}
await delay.Completion;
}
Upvotes: 1
Views: 257
Reputation: 101523
You need to call
delay.Complete();
to notify block that no more items will arrive. Then, after processing all current work (if any), block will go to completed state and delay.Completion
task will complete. As of now, your await delay.Completion
will never return.
Upvotes: 1