Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement the EventHandler Observer pattern in C #

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to realize the EventHandler observer mode in C#". In the daily operation, I believe that many people have doubts about how to realize the EventHandler observer mode in C#. The editor has consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "how to realize the EventHandler observer mode in C#"! Next, please follow the editor to study!

C # and java comparison: interfaces are used in java. C # uses the delegation mechanism and can be registered with the time + operator for direct multicast. In java, it is common to use a collection to hold the observer.

I. explanation

Publisher (Publisher) = observed (Observable) = event source (sender in EventObject,C# in java)

Subscriber (Subscriber) = observer (Observer) = recipient (inherit EventLister, interface, or Observer interface in java. Because of the delegation mechanism, C # does not need to inherit the interface, and directly press EventHandler to implement the callback method)

When something of interest to other classes or objects occurs, the class or object can notify them through events. The class that sends (or raises) the event is called the publisher, and the class that receives (or handles) the event is called the subscriber. In a typical C # Windows form or Web application, you can subscribe to events raised by controls such as buttons and list boxes. You can use the Visual C # integrated development environment (IDE) to browse the events published by the control and select the events to handle. IDE automatically adds empty event handler methods and code to subscribe to events.

EventHandler is a predefined delegate in C # designed to represent handler methods for events that do not generate data.

Public delegate void EventHandler (Object sender, EventArgs e) 2. The event has the following characteristics:

1. The publisher determines when the event is raised, and the subscriber determines what action to take in response to the event.

two。 An event can have multiple subscribers. A subscriber can handle multiple events from multiple publishers.

3. Events without subscribers are never called.

4. Events are typically used to notify users of actions such as button clicks or menu selection actions in a graphical user interface.

5. If an event has multiple subscribers, multiple event handlers are called synchronously when the event is raised. To invoke events asynchronously, see calling synchronous methods asynchronously.

6. You can use events to synchronize threads.

7. In the .NET Framework class library, events are based on EventHandler delegates and EventArgs base classes.

Instance code

Using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleAppEventArgs {public class Program {public 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 event pub.DoSomething (); Console.WriteLine ("Press Enter to close this window."); Console.ReadLine ();}} / customize an event class to store event information / public class CustomEventArgs: EventArgs public CustomEventArgs (string s) private string message Public string Message get {return message;} set {message = value;} / / broadcast event class public class Publisher / / declare an event public event EventHandler RaiseCustomEvent; public void DoSomething () / / DoSomething using EventHandler. / / you can also execute some other code OnRaiseCustomEvent (new CustomEventArgs ("Did something,hi this is the event message") before triggering the event; protected virtual void OnRaiseCustomEvent (CustomEventArgs e) / / defines a local variable to prevent the last subscriber from unsubscribing EventHandler handler = RaiseCustomEvent just after checking the null / / if there is no subscriber (observer), the delegate object will be null if (handler! = null) {/ / format the string e.Message + = String.Format ("at {0}", DateTime.Now.ToString ()) in the event message; / / this is the most important sentence. / / the handler executed at this time is already a multicast delegate (if multiple subscribers or observers are registered). / / since it is a multicast delegate, you can call each callback function in turn (since it is a callback function, the actual execution is determined by the subscriber class). / / A this is passed in, which represents the event source (or the publisher or the observed) handler (this, e);} / the class public class Subscriber private string id; public Subscriber (string ID, Publisher pub) id = ID used to register the event / / the action of registering should be carried out actively by subscribers, and you can unregister pub.RaiseCustomEvent + = HandleCustomEvent; / / at a later stage to implement the callback function. What kind of action is performed after the event. This is just a simple print message. Void HandleCustomEvent (object sender, CustomEventArgs e) / / this is the actual operation. Console.WriteLine (id + "received this message: {0}", e.Message);} at this point, the study on "how to implement the EventHandler Observer pattern in C#" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report