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
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