C# delegation and event delegation

Posted by laurajohn89 on Tue, 14 Dec 2021 12:11:00 +0100

C# delegation and event delegation

What is delegation?

1. Concept

   Delegate is similar to the pointer of a function in C or C + +. It is a reference type variable that holds a reference to a method. Reference Delegate can be changed at run time, especially for implementing event and callback methods. It comes from the System.Delegate class.
  generally speaking, entrustment is to let others do it. It is especially useful when you need to do an operation at an uncertain time. For example, as parents who are very responsible for the uncertain hunger of their children, they don't always need to ask their children if they are hungry, Just tell (entrust) their children to express (send) their hunger when they are hungry to prompt the parents (trigger the request). In this way, parents (main thread) are not required to ask (query) in real time. This greatly reduces the workload of parents.

   common function methods of delegation:

public object Invoke(Delegate method);
public object Invoke(Delegate method, params object[] args);

2. Code description delegate

public delegate void weituoFunction(string data, bool Cs);   //Define delegate
weituoFunction _weituoFunction;//Instantiate delegate

//WinForm loading
private void Form_Load(object sender, EventArgs e)
{
		//Delegate method for adding corresponding implementation
		_weituoFunction= new weituoFunction(RichTextboxAddDsiplay); 
}

//Defined event entry
private void OnPowerChange(object sender, EventArgs e)
{ 
		hungryShow("Iam hungry!",true);
}

//Method operation of delegate implementation
private void RichTextboxAddDsiplay(string data bool Cs)
{
	if (Cs)
	this.richTextBox_Display.AppendText(data + "\r\n");//true displays
}

//Definition and implementation of delegate function and transfer parameters
public void hungryShow(string data, bool Cs)
{
     this.Invoke(_weituoFunction, data, Cs);//Run delegate function
}


  I use a concise example to describe a delegate. It looks a little complex and winding. It is easy to understand after careful thinking. It is similar to the callback method. A delegate can also implement multiple methods or call multiple delegates at the same time. Parameters can be carried or not applicable. Two different parameters are used in the example.

What is an event delegate?

1. Concept

   Event Delegation is also called Event Delegation. It is a common technique for binding events. It can enable the underlying classes or methods to take the listening responsibility and trigger custom events.
  here's another simple example. When we were young, there was no such developed express delivery or such a powerful Internet. I often checked our mailbox downstairs. Each household had an iron box. When a letter arrives, the postman will put it in. We are not sure whether there is a letter in it, so we often open it when we have nothing to do. But the great opportunity is empty and nothing, which often disappoints me. Now it's different. What express SMS message, what Fengchao express wechat push message, etc. We no longer need to check whether we have received our own letters or express in the cabinet. These problems are handed over (entrusted) to the postman or express cabinet system, just as our users (the highest application layer) are handed over to the postman (the lower transport layer), and events are sent from bottom to top.

System. The public delegate void EventHandler(object sender, EventArgs e) in the EventHandler class is a method for event delegate behavior.

2. Code description event delegate

class Form1
{
   	//Function class instantiation
   	Mail _Mail= new Mail();
   	//Load WinForm framework
	private void Form_Load(object sender, EventArgs e)
	{	
		//Add delegate event handling
		_Mail.RxChange += OnReceivedChange;
		_Mail.RxStart();//Start receive thread
	}
	
	//Function method of receiving change event
	private void OnReceivedChange(object sender, EventArgs e)
	{ 
	   this.richTextBox_Display.AppendText( "You have a courier!\r\n");//true displays
	}
}


class _Mail
{
	public event EventHandler RxChange; //Define event delegation  
	private void OnDelegateChange(EventArgs eventArgs) //Event delegate definition
	{
	    this.RxChange?.Invoke(this, eventArgs);//Delegate the event function of this class
	}  
	//Start thread
	public void RxStart()
	{
			ReceiveMailThread = new Thread(new ThreadStart(RxThread));//Specify thread function
			ReceiveMailThread.IsBackground = true;//Can run in the background
			ReceiveMailThread.Name = "Receive mail";//Thread name
			ReceiveMailThread.Start();//Thread start
	}
	//Receive thread
	public void  RxThread()
	{  	         
         try
          {
               while (true)
              { 	
                   if(ReceiveMailMonitor()==true)   
                   this.OnDelegateChange(new EventArgs());//Use event delegation
               }
          }
          catch (Exception ex)
          {                
            ex.MessageBox.show(ex.Message,"Err");
          }
	       
	}
}

  class Form1 is the main class, class_ Mail is a branch function class. Note that they must first be in the same workspace_ The mail class delegates events to the delegate defined by EventHandler RxChange and passes them to Form1. In the main program, the OnReceivedChange method (_Mail.RxChange += OnReceivedChange;) is added to the instantiated object, so that the delegate event in _mailtriggers the work of the upper OnReceivedChange. An event delegate can also execute multiple events or multiple added methods. ReceiveMailMonitor() is a user-defined receive monitoring, which is not described in the code.

Topics: C# event delegate