C # custom events

Source: Internet
Author: User
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 );}}}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.