Ok, I downloaded a sample multithreaded CLient/Server TCP/IP chat project..I got hung up about delegates at first, but then I was soon to understand the basic concept.
Here is what I am wondering.
In the client class, I simply see
Simple. I understand this. All the code is in one class.Code:private delegate void CloseConnectionCallback(string strReason); ... // Call this to prevent cross-thread calls this.Invoke(new CloseConnectionCallback(this.CloseConnection), new object[] { Reason });
Now, for the part that I do not understand is in the Server project.
The server project has multiple classes, so i am assuming this is needed to fire an even across MULTIPLE classes.
Now a different classCode:public delegate void StatusChangedEventHandler(object sender, StatusChangedEventArgs e); public class StatusChangedEventArgs : EventArgs { private string EventMsg; public string EventMessage { get { return EventMsg; } set { EventMsg = value; } } // Constructor public StatusChangedEventArgs(string strEventArgs) { EventMsg = strEventArgs; } }
Yet a diferent classCode:public static event StatusChangedEventHandler StatusChanged; public static StatusChangedEventArgs e; public static void OnStatusChanged(StatusChangedEventArgs e) { StatusChangedEventHandler statusHandler = StatusChanged; if (statusHandler != null) { statusHandler(null, e); } } // To fire the event e = new StatusChangedEventArgs("User: " + strPacketData ); OnStatusChanged(e);
Code:private delegate void UpdateStatusCallback(string strMessage); public ChatServer() { InitializeComponent(); } public void server_StatusChanged(object sender, StatusChangedEventArgs e) { this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { e.EventMessage }); }Now, why not just use the simple method as in the first example? Am I right assuming that this is needed to fire events from multiple classes? Enlighten meCode:Server.StatusChanged += new StatusChangedEventHandler(server_StatusChanged);![]()




Reply With Quote