Is there such a synchronization tool as “single-item-sized async task buffer”?

后端 未结 3 899
隐瞒了意图╮
隐瞒了意图╮ 2021-01-21 06:44

Many times in UI development I handle events in such a way that when an event first comes - I immediately start processing, but if there is one processing operation in progress

3条回答
  •  滥情空心
    2021-01-21 07:30

    What you're describing sounds very similar to how TPL Dataflow's BrodcastBlock behaves: it always remembers only the last item that you sent to it. If you combine it with ActionBlock that executes your action and has capacity only for the item currently being processed, you get what you want (the method needs a better name):

    // returns send delegate
    private static Action CreateProcessor(Action executedAction)
    {
        var broadcastBlock = new BroadcastBlock(null);
        var actionBlock = new ActionBlock(
          executedAction, new ExecutionDataflowBlockOptions { BoundedCapacity = 1 });
    
        broadcastBlock.LinkTo(actionBlock);
    
        return item => broadcastBlock.Post(item);
    }
    

    Usage could be something like this:

    var processor = CreateProcessor(
        i =>
        {
            Console.WriteLine(i);
            Thread.Sleep(i);
        });
    
    processor(100);
    processor(1);
    processor(2);
    

    Output:

    100
    2
    

提交回复
热议问题