On Delegation Event and Asynchronous in C

  • 2021-12-12 05:24:20
  • OfStack

It has been almost one year since I first came into contact with c # programming. In the process of learning, there are many specious places all the time, which have not been understood until recently.

This article will introduce the usage first, and then judge the function.

1. Commissioning

Basic usage:

1. Declare a delegate type. Delegates are like 'Class' 1. After declaring one type of delegate, you can create multiple delegates with such characteristics. (Characteristics refer to return values and parameter types)

public delegate void SomeKindOfDelegate(string result);

2. Create a delegate of the delegate type created in 1.

public SomeKindOfDelegate aDelegate;

3. Add a response function for the specific delegate created in 2. The response function must conform to the 'Characteristics' in 1.


aDelegate +=new SomeKindOfDelegate(aFunctionThatJustForDelegate);
private void aFunctionThatJustForDelegate(string result)
{
MessageBox.Show(result);
}

4. After completing the above three steps, you can use Invoke to invoke the delegate. Invoke can choose which target function to call, which priority to call, and which parameters to call.

aDelegate.BeginInvoke("Hello~I'm being invoked!", null, null);

The above is the basic usage. In addition to this basic usage, you can also combine var, anonymous delegate, lambda delegate and other methods.

Complete code:


namespace wtfIsDelegate
{
 public delegate void SomeKindOfDelegate(string result);
 public partial class Form1 : Form
 {
  public event SomeKindOfDelegate aDelegate;
  public Form1()
  {
   InitializeComponent();
   aDelegate +=new SomeKindOfDelegate(aFunctionThatJustForDelegate);
   aDelegate.BeginInvoke("Hello~I'm being invoked!", null, null);
  }
  private void btnDelegate_Click(object sender, EventArgs e)
  {
  }
  private void aFunctionThatJustForDelegate(string result)
  {
   MessageBox.Show(result);
  }
 }
}

Usefulness of delegation:

The advantage of delegate is that it can be asynchronous (BeginInvoke), and it can also simplify the code when it is necessary to call multiple return values with the same parameters at the same time.

2. Events

Basic usage:

1. Define delegates.

public delegate void SomeKindOfDelegate(string result);

2. Define events.

public event SomeKindOfDelegate aDelegate;

3. Add a response function to the event.

process.Exited += new EventHandler(CmdProcess_Exited);

4. Specify the trigger (call) mode for the event. ("It can also be invoke directly without triggering mode")

Commentary:

In C #, every kind of 'Event' probably corresponds to its' Event Handler EventHandler '. For example, OutputDataReceived of Process corresponds to DataReceivedEventHandler, and for non-specific' Events', such as PasswordChanged, they all correspond to RoutedEventHandler or EventHandler, which are more general 'Event Handlers'. However, 'EventHandler' only acts as an intermediary, and we need to manually specify what to do after really triggering 'Event', like this:

process.Exited += new EventHandler(CmdProcess_Exited); // 注册进程结束事件 。

EventHandler was originally commissioned. For example

public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e);

Custom Events

Custom events are a delegate-like approach,

Custom events change the flow of a program in a sense, making the change of a certain condition change from'continuous query 'to'subscription and processing'.

Custom events require the following elements:

Event initiator, event subscription, and event handler. Parameters can be passed from the initiator to the handler.

The'initiation 'of an event can depend on some system message, such as' OnKeyDown ',' OnMouseClick '("I haven't seen the source code written like this yet"), or it can be called by itself when a certain condition is met (such as entering the same character twice) (in fact, receiving a system message is considered as' condition met '). "More event is written like this."

Some events have no obvious'initiator '.

What is the relationship between delegation and event

Delegates and custom events are used in a similar way. event can only be Invoke, delegate, Invoke can be anywhere. The way of calling also seems to be slightly different (the way of passing parameters)

event is more conservative/stable due to the difference of calling mode and parameter transmission. event is also easier to accept from the perspective of'understanding '.

delegate seems to be used more asynchronously (begin invoke). event is more used to do custom events.

What is the relationship between delegate and asynchronism

Asynchrony is a function that delegates can achieve (or'phenomena 'can also be). Asynchrony can be embodied in many other ways, such as multithreading (thread, threadpool, task, and so on).


Related articles: