Personal experience of event handling in c sharp

  • 2020-05-05 11:44:04
  • OfStack

A simple explanation of the   juky_huang   event:

An event is a message sent by an object to signal the occurrence of an operation. An action may be caused by a user interaction, such as a mouse click, or it may be triggered by some other program logic. The object that raises (triggers) an event is called the event sender. The object that captures the event and responds to it is called the event receiver.

In event communication, the event sender class does not know which object or method will receive (process) the event it raises. What is needed is a medium (or a pointer like mechanism) between the source and the receiver. NET   Framework   defines a special type (Delegate) that provides function Pointers.

Unlike other classes, the delegate class has a signature, and it can only reference methods that match its signature. In this way, a delegate is equivalent to a pointer to a type-safe function or a callback.

Steps to use events in C# :

Create a delegate
Associate the created delegate with a specific event (many of the events in the.Net library are already customized, so they have a delegate that will have the same signature as the delegate when writing the associated event handler -- the method we want to execute when an event occurs)
Write the event handler
Generate a delegate instance,
, with the written event handler Add the delegate instance to the list of events that produce the event object, also known as the subscription event
The flow of event generation and implementation in C# :

Define A as the instance that produces the event, and a as an event
that produces A Define B as the instance that receives the event and b as the method
that handles the event A
generates an a event (e.g., clicking on an Button generates an Click event) due to the user (programmer or user) or the system A notifies B
of this event through the delegate object in the event list B receives an event notification (actually B.b USES delegates to receive events)
Call the B.b method to complete the
event handling Here is an example of the classic introduction to C#, with some explanation:

//====================Connection.cs===========
// event definition, which is A
mentioned above //============================================
using   System;
using   System.Timers;

namespace   Ch12Ex02
{
///   < summary >
/// summary of   Connection  .
///   < /summary >
///  

public   delegate   void   MessageHandler(string   messageText); // create a delegate -- step 1
public   class   Connection
{
public   event   MessageHandler   MessageArrived; // associate the delegate created with a specific event, in this case MessageArrived   -- step 2*/
/* what is noteworthy about the above statement is that after the   MessageArrived method is associated with MessageHandler, the subsequent message delivery is realized through the MessageHandler delegate, so if you want to receive this message, you must be able to support the MessageHandler delegate, which means you must have the same signature as the  
private   Timer   pollTimer;
public   Connection()
{
//
//   TODO:   add the constructor logic
here //
pollTimer=new   Timer(100);
pollTimer.Elapsed+=new   ElapsedEventHandler(CheckForMessage);
}

public   void   Connect()
{
pollTimer.Start();
}

public   void   Disconnect()
{
pollTimer.Stop();
}

public   void   CheckForMessage(object   sender,ElapsedEventArgs   e)
{
Console.WriteLine("Check   for   message.");
Random   random=new   Random();
if((random.Next(9)==0)&&(MessageArrived!=null))
{
MessageArrived (" Hello   Mum!" ); // the programmer generates a message of his own, Hello   Mum!
}
}
}
}

//====================Display.cs===========
// the class that receives the event is B
mentioned above //=========================================
using   System;

namespace   Ch12Ex02
{
///   < summary >
///   Display  
///   < /summary >
public   class   Display
{
public   Display()
{
//
//   TODO:   add the constructor logic
here //

}

public void   DisplayMessage(string   message)   //a b (string   message {
Console.WriteLine("Message   Arrived:{0}",message);
}
}
}

//====================Class1.cs=================
// a console executable class that primarily USES instances of the above two classes
//==============================================
using   System;

namespace   Ch12Ex02
{
///   < summary >
///   Class1   abstract description.
///   < /summary >
class   Class1
{
///   < summary >
/// the main entry point of the   application.
///   < /summary >
[STAThread]
static   void   Main(string[]   args)
{
//
//   TODO:   add code here to launch the application
//

Connection   myConnection=new   Connection();
Display   myDisplay=new   Display();
myConnection. MessageArrived + = new   MessageHandler (myDisplay. DisplayMessage); // add the delegate to the current A event list -- steps 4 and 5

myConnection.Connect();
Console.ReadLine();
}
}
}

Code of note:
public     void   MessageHandler(string   messageText); // delegate definition
public   event   MessageHandler   MessageArrived; // defines an event and is associated with
on a delegate myConnection. MessageArrived + = new   MessageHandler (myDisplay. DisplayMessage); // generates a delegate instance and adds the   += notation to the event list. The   += notation is useful here
 

Related articles: