An event discussion

Source: Internet
Author: User

Two mechanisms of window: Drawing Mechanism Based on the event-driven message mechanism (Supplement: messages come from events, and different events generate different messages, it can also be considered that there is a one-to-one ing between events and messages)

----------------------------

Event mechanisms are embodied in multiple languages:

For example, C #: + =,-= (Supplement: The Event definition in C # is based on the delegate and can only trigger methods with the same signature as the delegate)

For example, Dojo: dojo. Connect, and dojo. Disconnect

For example, javascript: element. attachevent, element. detachevent, element. addeventlistener, element. removeeventlister

For example, flex:

Different technologies are similar, but they are also different. To extract universal principles, we need to be abstract and help from mathematics.

----------------------------

C # functions of the event:

1. Class A notification Class B: When event D occurs, execute method g

(Supplement: Classes A and B can be the same or different classes. Method G does not necessarily belong to Class A, and method G does not necessarily belong to Class B, method G may belong to a third-party class; Method G may be a function with or without parameters)

2. If the method G contains parameters, you can pass the parameters. Generally, there are two parameters: one is the event trigger sender and the other is the event parameter E.

----------------------------

C # event classification:

1. System Event: button. Click

2. Custom events: taskstartevent, taskdoingevent, and taskfinishedenvent

----------------------------

C # event triggering:

1. system trigger: When a button is clicked, the button. Click is triggered.

2. Custom triggering: taskstartevent, taskdoingevent, and taskfinishedenvent are triggered when ontaskstart, ontaskdoing, and ontaskfinished methods are executed.

----------------------------

ReferencesArticlePart of content:

*********************

Method 3: Event Callback

Public Delegate void mydelegate (string text );

Public partial class form2: form1

{

// Define the delegate event

Public event mydelegate myevent;

Public form2 (string text)

{

Initializecomponent ();

This. textbox1.text = text;

}

Private void btnchange_click (Object sender, eventargs E)

{

// Trigger the event and send the modified text back

Myevent (this. textbox1.text );

This. Close ();

}

}

Form1: C #Code

Public partial class form1: Form

{

Public int Index = 0;

Public String text = NULL;

Public form1 ()

{

Initializecomponent ();

}

Private void listbox1_selectedindexchanged (Object sender, eventargse)

{

If (this. listbox1.selecteditem! = NULL)

{

TEXT = This. listbox1.selecteditem. tostring ();

Index = This. listbox1.selectedindex;

Form2 form2 = new form2 (text );

// Register the myevent event of the form2_myevent Method

Form2.myevent + = new mydelegate (form2_myevent );

Form2.show ();

}

}

// Process

Void form2_myevent (string text)

{

This. listbox1.items. removeat (INDEX );

This. listbox1.items. insert (index, text );

}

}

******************************

Event is a very important concept.ProgramVarious events are triggered and received at all times: mouse click events, keyboard events, and various operating system events. An event is a message sent from an object. For example, if a user presses a button and a file changes, data on the socket reaches. The object that triggers an event is called the sender. The object that captures the event and responds to the event is called the receiver. An event can have multiple recipients.

In the asynchronous mechanism, events are a very common method for communication between threads. For example, you can click a button on the interface to execute a time-consuming task. The program starts a thread to process this task. a progress bar is displayed on the user interface to indicate the execution status of the user task. This function can be used to process events. The class that processes the task can be used as the message sender. When the task starts, the "taskstart" event is issued, and the "taskdoing" event is issued at different times during the task, parameters are included to describe the proportion of tasks. When the task ends, a "taskdone" event is sent to receive and process these events on the screen. In this way, the function is implemented, and the module coupling between the interface and the backend is also the lowest.

*****************************

Edit comment: An event is a process in which messages are sent and processed between two subsystems in a software system or between two modules or between two objects. In the object-oriented world, we can regard it as the behavior between two objects.

I. Nature of events

An event is a process in which messages are sent and processed between two subsystems in a software system or between two modules or between two objects. In the object-oriented world, we can regard it as the behavior between two objects.

The message sent between two objects generates an event for the sender, and an event must be processed when connected to the receiver. This message can be generated by user operations or an object in the software system.

Event Processing between objects 

As you can see, when an object generates an event, it requires object 2 to execute an action. This is the event mechanism.The object is the producer or sender of the event, and the object is the receiver or subscriber of the event. When an object generates a message, it must respond to and process the message. This is the essence of an event.

In the past, many software systems have adopted the event mechanism to handle many problems. For example, from Soft Interrupt Processing in the most essential computer systemMASMInJump,C/C ++Callback Function in. However, the more advanced the software system processes events or provides a lot of processing methods, the closer it is to human thinking, and the closer it is to machine thinking. Building a software system is essentially a process from machine thinking to human thinking.

Ii. Benefits of the event mechanism

1, Direct call

What are the advantages of using the event mechanism? Why does the event sender not directly call the processing functions provided by the event receiver?

Call Mechanism

The call mechanism between two objects, as shown in. ObjectBCall objectAFunction pointer or jump (assembly language. The result of this method is:AAndBTightly coupled, that isBPairAHas a strong dependence. Can be viewedBIs the event publisher,AIs the response and handling of events. However, the event mechanism is theoretically far-fetched. The idea of implementing the same thing is different.

Assume that an object exists.CResponse alsoB. Then, according to the above mechanism, the object needs to be modifiedBCode, call objectC. This mechanism creates a very strong dependency. Code Modification and extension are very troublesome. The more objects there are, the more relationships there are, the more complex the system is. If there are many objects in a system and there are many such dependencies, this call relationship will be very complicated and will affect the robustness and superiority of the system.

2Callback mechanism

If you followC #Idea of delegation,BSome callback pointers to event processing functions must be provided in advance. In this way, other objects, suchAAndCModify the callback pointer and contact your method. However, the coupling relationship between them is simpler than above.

Callback mechanism 

The idea of the callback mechanism is close to the concept of delegation. In fact, the delegation is essentially similar to the callback pointer, but it is more advanced in concept. ObjectBAs the event publisher, define some callback function pointers in advance, and then call the functions pointed to by these pointers locally. Event subscriber or handlerAAndCWhat you do is assign values to these null pointers and assign the event handling methods to them to implementBCallAAndC.

InCOrC ++The most similar to delegate is the function pointer. However, function pointers can only reference static functions, while delegates can reference static methods and instance methods. When a delegate references an instance method, the delegate not only stores the reference to the method entry point, but also stores the reference to the class instance for which the method is called. Unlike function pointers, delegation is object-oriented, type-safe, and secure.

Iii. Implementation of the event mechanism

1Limitations of delegation

If delegate is used, the event publisherBLet's assume it publishes an event.EFor eventsEIt already knows thatAAndCThe object needs to subscribe to this event. Therefore, it declares two delegate object references (essentially similar to a function pointer), and thenAAndCObject To use a callback-like mechanism to subscribe to and respond to events.

If there is an object laterDYou also need to subscribeBEventEWhat should it do? One scenario isDModifyBTo package your processing method into a delegate object and pay it. In this way,DIt's a snatch.AOrC. Otherwise, you need to modifyBCode, add a similar delegate object reference, so thatD.

The consequence is that the event publisherBYou need to declare the reference variables of many delegate objects. The result is that the Code maintenance is messy, and there are a lot of users, and the dependency is not easy to understand, and errors are prone.

2, Event Introduction

With delegation, it provides functions similar to callback. However, the callback mechanism requires the joint participation and efforts of both event publishers and event subscribers. That is, each time a subscriber is added, the publisher object must provide a delegate reference to hook the subscriber.

If the publisher of an event does not subscribe to it after publishing an event, the subsequent processing is handed over to the user, and the publisher no longer cares about the issue of the event handler.

Subscription Mechanism 

C #Event Events are actually subscribed to by this subscription mechanism. The publisher does not need to care about the subscriber.

C #The event provides the subscriber with the registration and anti-registration functions for event response. Subscription and revocation are completely the actions of the event receiver.

C #The implementation of the event mechanism includes the following steps:

1,The event publisher defines a delegate type;

2,The event publisher defines an event and associates it with the defined delegate.

3,The event subscriber must generate a delegate instance and add it to the delegate list.

Therefore, eventsEventIt can be viewed as an event list. A subscriber can register and revoke its own response and processing mechanisms, but it cannot change the entire list (in principle ). Therefore, it provides a stronger and safer way.

4. code example of the event mechanism

Application Structure Diagram

The event publishing object publishes an event. The event subscription object subscribes to and processes the event.

 Using  System;
Namespace Eventexample
{
/// <Summary>
/// Mainclass: Main Application class
/// </Summary>
Class Mainclass
{
/// <Summary>
/// The main entry point of the application.
/// </Summary>
[Stathread]
Static Void Main ( String [] ARGs)
{
Eventpublisher publisher = New Eventpublisher ();
Eventreader1 reader1 = New Eventreader1 (publisher );
Eventreader2 reader2 = New Eventreader2 (publisher );
Publisher. dosomthing ();
Console. writeline ( " This program already finished! " );
Console. Readline ();
}
}
/// <Summary>
/// Eventpublisher: the publisher of the event.
/// </Summary>
Public Class Eventpublisher
{
// The first step is to declare the delegation
Public Delegate Int Sampleeventdelegate ( String Messageinfo );
// Step 2: declare the events related to the above Delegation
Public Event Sampleeventdelegate sampleevent;
Public Eventpublisher ()
{
}
Public Void Dosomthing ()
{
/* ... */

// Event triggering
If ( This . Sampleevent ! = Null )
{
This . Sampleevent ( " Hello world! " );
}
/* ... */
}
}
/// <Summary>
/// Eventreader1: subscriber 1 of the event.
/// </Summary>
Public Class Eventreader1
{
Public Eventreader1 (eventpublisher publisher)
{
Publisher. sampleevent + =
New Eventexample. eventpublisher. sampleeventdelegate (responseevent );
}
Private Int Responseevent ( String MSG)
{
Console. writeline (msg + " --- This is from reader1 " );
Return 0 ;
}
}
/// <Summary>
/// Eventreader2: Event subscriber 2.
/// </Summary>
Public Class Eventreader2
{
Public Eventreader2 (eventpublisher publisher)
{
Publisher. sampleevent + =
New Eventexample. eventpublisher. sampleeventdelegate (responseevent );
Publisher. sampleevent + =
New Eventexample. eventpublisher. sampleeventdelegate (responseevent );
}
Private Int Responseevent ( String MSG)
{
Console. writeline (msg + " --- This is from reader2 " );
Console. writeline ( " Please: Down enter key! " );
Console. Readline ();
Console. writeline ( " OK " );
Return 0 ;
}

}

}

Program running result

Summary: Events published by event publishers can be viewed as a list of callback function pointers provided externally. The capacity of this list can be dynamically increased. Event subscriber can register an event to this list or cancel the registration, but it cannot be changed in principle or affect the registration of other subscriber. The event publisher correctly uses the event mechanism by two means: one is to defineDelegateThe delegate type. The event subscriber can only define the event handling method according to this type. The second is to define the Delegate-relatedEventSo that the subscriber is only responsible for registering and revoking his/her own processing process, rather than affecting others' processing processes at will.

From the running result andReader2The object registers the same processing method.The premise is that for an event, the same subscriber can register the same processing process multiple times, and this method will eventually be executed.Multiple times.

The order of methods in the execution event subscription list cannot be guaranteed. In addition, the synchronous call method is used here. Other functions will be executed only after one response function is executed. If the method is not blocked (including waiting for user input), asynchronous calling is required.



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.