// The following pattern should be used for the method that raises the event: // The OnMsgArrived method raises the event by invoking the delegates. // The sender is always "this", the current instance of the class. // Note: For classes designed to be subclassable, the following should be a protected virtual method. // Making it protected virtual provides a way for a subclass to handle the event using an override. // Naming convention: On<EventName> protected virtual void OnMsgArrived(MsgArrivedEventArgs me, object excludeClient) { if (MsgArrivedHandler != null) { // Send message to all clients except 'excludeClient' if (excludeClient == null) { MsgArrivedHandler(this, me); // sender is NULL since this is a static method and there is no object } else { Delegate[] DelegateList = MsgArrivedHandler.GetInvocationList(); for (int i = 0; i < DelegateList.Length; i++) { if (DelegateList[i].Target != excludeClient) { ((MsgArrivedEventHandler)DelegateList[i])(this, me); } } } } }
private void onMsgArrived(object sender, MsgArrivedEventArgs me) { Console.WriteLine("Msg arrived (Client {0}): {1} Server: {2}", clientName, me.Message, sender.ToString()); }
public void SendMsg(string msg, object excludeClient) { MsgArrivedEventArgs me = new MsgArrivedEventArgs(msg); OnMsgArrived(me, excludeClient); }