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.
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. In the “add” part of the property you could call the added delegate for any previous messages.