然后您可以编写类似的内容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<Message> messages = new Subject<Message>();public void GotNewMessage(Message msg){ messages.OnNext(msg);} 注意:这尚未准备就绪,但显示了操作方法的基本知识.根据您在何处提示消息,有更好的方法来创建要订阅的Observable.更多参考: http://www.introtorx.com/ https://msdn.microsoft. com/en-us/library/hh242985(v = vs.103).aspx 如果使用事件接收到您的消息,则可以将事件链接到RX流,请参见 https://msdn.microsoft.com/zh-CN/library/hh242978(v = vs.103).aspx 和 https://msdn.microsoft.com/en -us/library/system.reactive.linq.observable.fromeventpattern(v = vs.103).aspx 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 100 instances or when 1 minute has passed.Basically:List<Message> messages;public void GotNewMessage(Message msg){ messages.add(msg); if (messages.count() == 100 || timer.elapsed(1 minute)) { SendMessages(messages); messages.clear() }}I just can't seem to figure out how to implement this without an excessive use of locks which will slow down the process considerably. Does anyone know of a good way to implement such a system? Thanks in advance. 解决方案 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.NETYou could then write something likevoid Main(){ messages .Buffer(TimeSpan.FromMinutes(1), 100) // Buffer until 100 items or 1 minute has elapsed, whatever comes first. .Subscribe(msgs => SendMessages(msgs)); }Subject<Message> messages = new Subject<Message>();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).aspxIf 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 这篇关于C#.NET-带计时器的缓冲消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-23 14:17