C#.NET-带计时器的缓冲消息 [英] C# .NET - Buffer messages w/Timer
问题描述
我需要实现一个基于时间的消息缓冲系统.
我需要做的是存储类的实例,然后在达到100个实例或经过1分钟后将它们转发给其他人.
基本上:
List<Message> messages;
public void GotNewMessage(Message msg)
{
messages.add(msg);
if (messages.count() == 100 || timer.elapsed(1 minute))
{
SendMessages(messages);
messages.clear()
}
}
我似乎无法弄清楚如何在不过度使用锁的情况下实现这一点,这会大大减慢该过程.有谁知道实现这种系统的好方法?预先感谢.
有一个很棒的库可以满足此类需求(将时间与序列结合),它是Reactive Extensions.参见 https://github.com/Reactive-Extensions/Rx.NET >
然后您可以编写类似的内容
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.
更多参考:
如果使用事件接收到您的消息,则可以将事件链接到RX流,请参见 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.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<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:
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
这篇关于C#.NET-带计时器的缓冲消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!