C# .NET - Buffer messages w/Timer

后端 未结 2 1014
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-24 19:22

I need to implement a message buffering system that is also timed based.

What I need to do is store instances of my class and then send them forward either when I reach

2条回答
  •  深忆病人
    2021-01-24 19:36

    There is a fantastic library for these kind of requirements (combine time with sequences), it is Reactive Extensions. See https://github.com/Reactive-Extensions/Rx.NET

    You could then write something like

    void Main()
    {
        messages
            .Buffer(TimeSpan.FromMinutes(1), 100) // Buffer until 100 items or 1 minute has elapsed, whatever comes first.
            .Subscribe(msgs => SendMessages(msgs));     
    }
    
    Subject messages = new Subject();
    
    public void GotNewMessage(Message msg)
    {
        messages.OnNext(msg);
    }
    

    Note: this is not production ready but it shows the basic of how to do it. Depending on where you het the messages from there are better ways to create an Observable to subscribe to.

    More references:

    • http://www.introtorx.com/
    • https://msdn.microsoft.com/en-us/library/hh242985(v=vs.103).aspx

    If your message are received using an event you can link the event to a RX stream, see https://msdn.microsoft.com/en-us/library/hh242978(v=vs.103).aspx and https://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.fromeventpattern(v=vs.103).aspx

提交回复
热议问题