"Agents" and "events" in C #

Source: Internet
Author: User
Tags implement readline

Events are a very important concept, and our programs trigger and receive events at all times: mouse clicks, keyboard events, and various events that handle the operating system. The so-called event is a message sent by an object. For example, a user presses a button, a file changed, the socket on the data arrived. The object that triggers the event is called the Sender (sender), and the object that captures the event and responds is called the receiver (receiver), and an event can have multiple recipients. In asynchronous mechanisms, events are a very common way of communicating between threads. For example, the user presses a button on the interface to perform a time-consuming task. The program starts a thread at this time to handle the task, and a progress bar is displayed in the user interface indicating the status of the user's task execution. This feature allows you to use events for processing. The class that handles the task can be used as the sender of the message, and when the task begins, the "Taskstart" event is issued, the "Taskdoing" event is issued at different times in the task, and the ratio of the task is carried with the parameters, and the "Taskdone" event is issued when the task ends. Receive and handle these events in the screen. This enables functionality, and the interface and background perform the task's module coupling degree is also the lowest. Specifically speaking of the C # language, the implementation of the event relies on the concept of "agent" (delegate) to understand the agent first. The proxy (delegate) delegate is a type in C # that is actually a class that holds a reference to a method. Unlike other classes, the delegate class can have a signature (signature), and it can only hold a reference to the method that matches its signature. The functionality it implements is very similar to the function pointers in C + +. It allows you to pass the method M of Class A to the object of another class B, so that the object of Class B can call this method M. However, compared with function pointers, delegate has many advantages that are not available in function pointers. First, a function pointer can only point to a static function, while delegate can refer to static functions and non-static member functions. When referencing a non-static member function, delegate not only holds a reference to this function's entry pointer, but also holds a reference to the class instance that called the function. Secondly, compared with function pointers, delegate is an object-oriented, type-safe, and reliable controlled (managed) object. That is, runtime can ensure that delegate points to an effective method, and you need not worry that delegate will point to an invalid address or a cross-border address. Implementing a delegate is simple, with the following 3 steps to implement a delegate:1. Declares a delegate object that should have the same parameter and return value type as the method you want to pass.2. Create the delegate object and pass the function you want to pass in as a parameter. 3. In the place where you want to implement the asynchronous call, the method is invoked by the object created in the previous step. The following is a simple example: public class Mydelegatetest {//step 1, declaring delegate object public delegate void MyDelegate (string name);//This is the way we want to pass, It has the same parameter and return value type as the mydelegate public static void Mydelegatefunc (string name) {Console.WriteLine ("Hello, {0}", name); publi c static void Main () {//step 2, Create delegate object MyDelegate MD = new MyDelegate (mydelegatetest.mydelegatefunc);//Step 3, call Delega Te md ("sam1111"); The output result is: Hello, sam1111 below Let's look at how events are handled: event handling in the events (event) C # is actually a delegate with a special signature, as follows: public delegate void MyEventHandler (object sender, MyEventArgs e); Of these two parameters, sender represents the event sender, and E is the event argument class. The Myeventarg class is used to contain event-related data, and all event parameter classes must derive from the System.EventArgs class. Of course, if your event does not contain special parameters, then you can use the System.EventArgs class as an argument directly. Combined with the implementation of delegate, we can boil down the implementation of the custom event to the following steps: 1: Define the object type, it has two parameters, the first parameter is the event sender object, and the second parameter is the event parameter class object. 2: Define the event argument class, which should derive from the System.EventArgs class. If the event takes no arguments, this step can be omitted. 3: Defines an event-handling method that should have the same parameter and return value type as the delegate object. 4: Define the event object with the Events keyword, which is also a delegate object. 5: Add the event to the event queue with the + = operator (= operator can remove the event from the queue). 6: In the place where the event needs to be triggeredParty writes the event trigger method in a way that invokes delegate. In general, this method should be a protected access restriction that cannot be invoked as public, but can be inherited by the quilt class. The name can be OnEventName 7: Invoke the Event trigger method to trigger the event where appropriate. Here is an example that mimics the patterns of containers and controls, triggers an event by a control, captures it in a container, and processes it. Trigger of event:/**//// the trigger for the///event///public class Control {public delegate void Somehandler (object sender, System.EventArgs e);/**//** * can be provided by System System.even Thandler, here to illustrate the situation using its own defined delegate * If you need to use your own defined type in the parameters of the event, also define your own delegate///public event System.EventHandler Someevent;   public event Somehandler Someevent; The delegate used here must be//this consistent with the reputation of the event. Someevent + = new System.EventHandler (this. Control_someevent); This. Someevent + = new Somehandler (this. Processsomeevent); public void Raisesomeevent () {EventArgs e = new EventArgs (); Console.Write ("Please input ' a ':"); string s = Console.ReadLine (); Triggers an event if the user enters a small a and does not trigger if (s = = "a") {someevent (this, e);}} The trigger of the event handles the event on its own, and the parameter of this method must be consistent with the reputation of the agent in the same private void Processsomeevent (object sender, EventArgs e) {Console.WriteLine (" Hello "); The recipient of the event:/**//// ///event receiver and handler///Class Container {Private Control CTRL = new control (), public Container () {//The delegate used here must be consistent with the reputation of the event//ctrl. Someevent + = new EventHandler (this. Onsomeevent); Ctrl. Someevent + = new Control.somehandler (this. Responsesomeevent); Ctrl. Raisesomeevent (); The public static void Main () {Container pane = new Container ();//This ReadLine is suspended by the program, otherwise the screen will flash and nothing can be seen Console.ReadLine ();} This is the recipient of the event's response to the event private void Responsesomeevent (object sender, EventArgs e) {Console.WriteLine ("Some event occur!");}   The results of the program running are as follows: Please input ' a ': A Hello Some event occur! Event applications such as the following requirements need to be implemented: a child window pops up in the main screen of the program. At this point, the main screen can still receive the user's action (the child window is not modal). child window, depending on the results of the operation to display different data on the main screen. I found that some programmers to achieve this function: the main screen after the child window, put its own pointer to the child screen, and then use this pointer in the child screen, call the main screen to provide the method to change the main screen data display. This can achieve the goal, but there is a strong coupling between the modules. Generally speaking, the call between modules should be One Direction: module A calls Module B, module B should not reverse call a, otherwise it destroys the level of the program, strengthens the coupling degree, and makes the function change and append become very difficult. At this point the correct approach should be in the operation of the child window to emit a variety of events, and the main window to capture these events for processing, each module to concentrate on their own things, do not need to interfere with other modules of things. Delegate and event in the blog:http://blog.csdn.net/sam1111/c# of reference sam111


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.