Briefly introduce the usage of delegation, events and asynchronous in C#

黄舟
Release: 2017-03-24 11:17:40
Original
1835 people have browsed it

This article mainly introduces the related knowledge of delegation, events and asynchronous in C#. Has very good reference value. Let’s take a look with the editor below

It has been almost a year since I first came into contact with C# programming. In the learning process, there are many things that have always been paradoxical, and I didn't understand them until recently.

This article will first introduce the usage and then evaluate the function.

1. Delegate

Basic usage:

1. Declare a delegate type. Delegates are like 'classes'. After declaring a delegate, you can create multiple delegates with this characteristic. (Features refer to return values ​​and parameter types)

public delegate void SomeKindOfDelegate(<a href="http://www.php.cn/wiki/57.html" target="_blank">string</a> result);

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

public SomeKindOfDelegate aDelegate;

3. Add a response function to 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);
}
Copy after login

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

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

The above is the basic usage, in addition to this basic usage , and can also be combined with var, anonymous delegation, lambda delegation 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&#39;m being invoked!", null, null);
  }
  private void btnDelegate_Click(object sender, EventArgs e)
  {
  }
  private void aFunctionThatJustForDelegate(string result)
  {
   MessageBox.Show(result);
  }
 }
}
Copy after login

The use of delegation:

The advantage of delegation is that it can implement asynchronous (BeginInvoke), and can also be used when certain needs are required Simplify the code when multiple calls with the same parameters and return values ​​are made at the same time.

2. Events

Basic usage:

1. Define delegation.

public delegate void SomeKindOfDelegate(string result);

2. Define events.

public event SomeKindOfDelegate aDelegate;

3. Add a response function for the event.

process.Exited += new EventHandler(CmdProcess_Exited);

4. Specify the triggering (calling) method for the event. ([You can also invoke directly without triggering])

Explanation:

In C#, each 'Event' probably corresponds to its 'Event HandlingEventHandler'. For example, the OutputDataReceived event of the Process class corresponds to the DataReceivedEventHandler. For non-specific 'events', such as PasswordChanged, they all correspond to more general 'event handlers' such as RoutedEventHandler or EventHandler. However, 'EventHandler' only acts as an intermediary. What to do after the 'Event' is actually triggered, we need to manually specify, like this:

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

EventHandler is also a delegate. For example

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

Custom event

Custom event is a method similar to delegation,

Custom event In a sense, it changes the flow of the program, so that changes in a certain condition are transformed from 'continuous query' to a 'subscription and processing' relationship.

Custom events require the following elements:

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

The 'initiation' of an event can depend on some kind of system message, such as 'OnKeyDown', 'OnMouseClick' ([I have not seen source code written like this]), and also It can be called by itself when a certain condition is met (for example, the same character is entered twice) (in fact, receiving a system message is also considered as 'condition met'). [More events are written like this]

Some events have no obvious ‘initiator’.

What is the relationship between delegation and events

The usage of delegation and custom events is very similar. Event can be Invoked only inside the class. If it is a delegate, it can be Invoked anywhere. The calling method seems to be slightly different (parameter passing method)

Due to the difference in calling method and parameter passing, event appears to be more conservative/stable. Events are also easier to ‘understand’ and accept.

delegate seems to be more used for asynchronous (begin invoke). Event is more used for custom events.

What is the relationship between delegation and asynchronous

Asynchronous is a function that delegation can achieve (or it can also be called a 'phenomenon'). Asynchronous can be embodied in many other ways. , such as multi-threading (thread, threadpool, task, etc.).

The above is the detailed content of Briefly introduce the usage of delegation, events and asynchronous in C#. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!