且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

备用数据流来与BroadcastBlock保证交付

更新时间:2022-11-02 23:06:22

假设你想通过广播同时使目标块接收时间来处理一个项目该项目同时需要修改广播提供给所有块的数量在同一时间,然后异步等待所有的一起来移动到下一个数字之前接受它:

Assuming you want to handle one item at a time by the broadcaster while enabling the target blocks to receive that item concurrently you need to change the broadcaster to offer the number to all blocks at the same time and then asynchronously wait for all of them together to accept it before moving on to the next number:

var broadcaster = new ActionBlock<int>(async num => 
{
    var tasks = new List<Task>();
    foreach (var block in blocks)
    {
        tasks.Add(block.SendAsync(num));
    }
    await Task.WhenAll(tasks);
}, execopt);

现在,在这种情况下,你不必下班后等着你可以稍微优化,同时还返回一个awaitable任务:

Now, in this case where you don't have work after the await you can slightly optimize while still returning an awaitable task:

ActionBlock<int> broadcaster = new ActionBlock<int>(
    num => Task.WhenAll(blocks.Select(block => block.SendAsync(num))), execopt);