C # eventhandler observer mode for delegated events and comparison with Java

Source: Internet
Author: User

C # comparison with Java: interfaces are used in Java.

C # Use the delegate mechanism. When available, use the + operator for registration and direct multicast.
In Java, a set is generally used to save the observer.

Publisher = observable = event source (eventobject in Java, Sender in C)

Subscriber = observer (observer) = Receiver (Java inherits eventlister, interface, or observer interface, C # because of the delegate mechanism, do not need to inherit interface, implement the callback method directly by eventhandler)

When other classes or objects are concerned, classes or objects can notify them through events. The class for sending (or triggering) events is called "publisher", and the class for receiving (or processing) events is called "subscription ".

In typical C # windows forms or web applications, you can subscribe to events caused by controls (such as buttons and lists. You can use Visual C # integrated development environment (IDE) to browse events published by controls and select the events to process. IDE automatically adds the empty event handler method and the Code for subscribing to the event.


Eventhandler is a predefined delegate in C # and is used to process events that do not generate data.

public delegate void EventHandler(Object sender,EventArgs e)

Event Overview

Events have the following features:

  • The publisher determines when an event is triggered, and the user determines the operation to be performed to respond to the event.

  • An event can have multiple subscribers. One subscriber can process multiple events from multiple publishers.

  • Events without subscribers will never be called.

  • Events are usually used to notify users of operations (for example, click a button in the graphic user interface or select a menu ).

  • If an event has multiple subscribers, multiple event handlers are synchronously called when the event is triggered. To call events asynchronously, see call synchronous methods in asynchronous mode.

  • You can use the event synchronization thread.

  • In the. NET Framework class library, events are based on the eventhandler delegate and eventargs base class.

See the following code for details!

The following example demonstrates the above steps, which will customize the eventargs class andEventhandler <t>Used as the event type.

The msdn instance is not bad. I used it directly. I translated it. The key part has been commented out!

Namespace consoleapplication2 {using system; using system. collections. generic; // customize an event class to save the event information. Public class customeventargs: eventargs {public customeventargs (string s) {message = s;} private string message; public String message {get {return message;} set {message = value ;}}} // broadcast event class publisher {// use eventhandler <t> to declare an event public event eventhandler <customeventargs> raisecust Omevent; // This method does something. Then an event is triggered. Public void dosomething () {// dosomething ............ // You can also execute some other code onraisecustomevent (New customeventargs ("did something, Hi this is the event message") before triggering the event;} // use the virtual method, the subclass can be rewritten. To allow Derived classes to override the event invocation behavior protected virtual void onraisecustomevent (customeventargs e) {// defines a local variable, it is prevented that the last subscriber just unsubscribes to eventhandler <customeventargs> handler = raisecustomevent after checking NULL; // if no subscriber (observer) exists, the delegate object will be null if (handler! = NULL) {// format the string e in the event message. message + = string. format ("at {0}", datetime. now. tostring (); // This is the most important sentence. // The Handler executed at this time is already a multicast delegate (if multiple subscribers or observers register ). // Since it is a multicast delegate, you can call each callback function in sequence (since it is a callback function, the actual execution is determined by the subscriber class ). // This indicates the event source (or both the publisher or observer) handler (this, e );}}} // class subscriber {private string ID; public subscriber (string ID, publisher pub) {id = ID; // register an event, use the C #2.0 syntax // register this action. A subscriber must take the initiative and can cancel the registration later. raisecustomevent + = handlecustomevent;} // implements the callback function. What operations will be performed after an event occurs. Here is just a simple print of information. Void handlecustomevent (Object sender, customeventargs e) {// This is the actual operation. Console. writeline (ID + "received this message: {0}", E. message) ;}} class class1 {static void main (string [] ARGs) {publisher pub = new publisher (); subscriber sub1 = new subscriber ("sub1", pub ); subscriber sub2 = new subscriber ("sub2", pub); // call this method to generate the event pub. dosomething (); // keep the console window open console. writeline ("press enter to close this window. "); console. readline ();}}}


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.