C # custom events are different from Java and involve delegation. The following code includes the whole process from event definition to event triggering and execution.
Using system; using system. collections. generic; using system. LINQ; using system. text; using system. timers; // using system. timers; namespace eventtest {// defines a delegate messagehandler, which can be considered as a class. Public Delegate void messagehandler (string messagetext); Class connections {// defines an event messagearrive, which is the delegated instance public event messagehandler messagearrive; private timer polltimer; private Static random = new random (); Public connections () {This. polltimer = new timer (); polltimer. elapsed + = new elapsedeventhandler (Display);} public void connect () {polltimer. start ();} public void disconnect (){ Polltimer. stop ();} public void display (Object source, elapsedeventargs e) {console. writeline ("New message coming"); If (random. next (9) = 0 & messagearrive! = NULL) {// trigger messagearrive event messagearrive ("New message arrived, and has been handled successfully");} static void main (string [] ARGs) {connections connector = new connections (); display displayor = New Display (); // assign a delegate instance to the messagearrive event. The parameter is the displaymessage method, the parameters of the method must be consistent with those of the delegate class. Connector. messagearrive + = new messagehandler (displayor. displaymessage); connector. connect (); console. readkey () ;}} public class display {public void displaymessage (string text) {console. writeline (text );}}}