简体   繁体   English

加载列表和订阅事件的正确方法

[英]Proper way to load a list and subscribe to event

Im writing a simple client server app. 我正在编写一个简单的客户端服务器应用程序。 On the client side I set up a singleton instance of class to do all communication with the server. 在客户端,我设置了class的单​​例实例来与服务器进行所有通信。 When new messages come in, I store them in a collection and then fire off an event. 当收到新消息时,我将它们存储在一个集合中,然后触发一个事件。 Any forms that are open and are subscribed to the event will then receive the message and process it. 然后,打开并预订该事件的任何表单都将接收到该消息并进行处理。

My problem is that if a form opens up after messages have been received, how do I send it the previously received messages and subscribe to new ones without missing any messages, or getting one twice? 我的问题是,如果在收到邮件后打开了表单,我该如何发送先前收到的邮件并订阅新邮件而又不丢失任何邮件或收到两次?

Form Code 表格代码

private void Form_Load(object sender, EventArgs e)
{
        handleMsgRec = new EventHandler<MsgEventArgs>(MsgReceived);        

        Comm.Instance.LoadMsgs(Msgs);

        Comm.Instance.MsgReceived += handleMsgRec;
}

Server Communication Code 服务器通讯代码

private static ReaderWriterLockSlim rw = new ReaderWriterLockSlim();

public void LoadMsgs(List<MsgObject> msgs)
{
        rw.EnterReadLock();
        Messages.ForEach(f => msgs.Add(f));
        rw.ExitReadLock();
}

edit: I dont think i explained myself well enough. 编辑:我认为我对自己的解释不够好。 I already am storing all of the messages that I receive. 我已经存储了收到的所有消息。 My concern is that between the time I load the messages and subscribe to the event, that a new message could come in that I would miss. 我担心的是,在我加载消息和订阅事件之间,可能会收到一条新消息,我会错过。 Or if I subscribe to the event first and then load the messages, that I could wind up receiving a message twice. 或者,如果我先订阅该事件然后加载消息,那么我可能会收到两次消息。

As Hans already mentioned: Store the previously received messages. 正如汉斯已经提到的:存储以前收到的消息。

Additionaly you could use a property for the MsgReceived event. 另外,您可以为MsgReceived事件使用一个属性。 In the "add" part of the property you could call the added delegate for any previous messages. 在属性的“添加”部分中,您可以为任何先前的消息调用添加的委托。

public event EventHandler<MsgEventArgs> MsgReceived
{
    add
    {
        foreach (MsgObject mo in msgs)
            value(this, new MsgEventArgs() { Message = mo });

        ...
    }
    remove
    {
        ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM