A brief introduction to delegates in C #, events and asynchronous usage

Source: Internet
Author: User
This article mainly introduces the related knowledge of delegate, event and asynchronous in C #. Has a good reference value. Let's take a look at the little series.

It has been almost a year since I first approached C # programming. In the course of learning, there are many places that are always specious, until recently to understand.

This article will first introduce the usage, post-judgement function.

First, the Commission

Basic usage:

1. Declare a delegate type. A delegate is like a ' class ', and after declaring a delegate, it is possible to create multiple delegates with this type of feature. (characteristic, refers to the return value, parameter type)

public delegate void SomeKindOfDelegate(string result);

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

public SomeKindOfDelegate aDelegate;

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

Adelegate +=new somekindofdelegate (afunctionthatjustfordelegate);p rivate void Afunctionthatjustfordelegate (string Result) {MessageBox.Show (result);}

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

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

Above is the basic usage, in addition to this basic usage, but also can be combined with Var, anonymous delegate, lambda delegate and other methods.

Full code:

namespace wtfisdelegate{public delegate void Somekindofdelegate (string result), public partial class Form1:form {  p Ublic 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);  } }}

Use of a delegate:

The advantage of a delegate is that it can be implemented asynchronously (BeginInvoke), and it can be simplified in situations where it is necessary to invoke multiple identical parameters and return values at the same time.

II. Events

Basic usage:

1. Define the delegate.

public delegate void SomeKindOfDelegate(string result);

2. Define the event.

public event SomeKindOfDelegate aDelegate;

3. Add a response function for the event.

process.Exited += new EventHandler(CmdProcess_Exited);

4. Specify the trigger (Invoke) mode for the event. ("can also not trigger the way, direct invoke")

Explanation:

In C #, each of the ' event events ' probably corresponds to its ' event processor EventHandler '. For example, the Outputdatareceived event of the process class corresponds to Datareceivedeventhandler, for nonspecific ' events ', such as passwordchanged, Their unification corresponds to the more general ' event handlers ' of Routedeventhandler or EventHandler. However, ' EventHandler ' also serves as an intermediary role that really triggers what to do after ' Event ' and requires us to specify it manually, like this:

Process. Exited + = new EventHandler (cmdprocess_exited); Registers the process end event.

EventHandler was originally commissioned. Like what

public delegate void Datareceivedeventhandler (object sender, Datareceivedeventargs e);

Custom events

A custom event is a delegate-like way,

Custom events Change the process of a program in a sense, making changes in a condition change from ' constant querying ' to ' subscription and processing '.

The custom event requires several elements:

The initiator of the event, the subscription to the event, and the handler for the event. Arguments can be passed between the initiator and the handler.

An event's ' initiation ' can depend on some kind of system message, such as ' OnKeyDown ', ' Onmouseclick ' ("I haven't seen the source code so far"), or it can be called when a condition is reached (such as two input of the same character) (actually receiving a system message is considered Conditions '). "More of the event is written out."

There are some events, and there is no obvious ' initiator '.

What is the relationship between delegates and events?

Delegates and custom events are very similar to how they are used. Event can be invoke,delegate only if the interior of the class can be used as an Invoke. The method of invocation seems to be slightly different (the method of transmitting parameters)

The event appears to be more conservative/stable due to the difference between the invocation and the transfer parameters. The event is also easier to accept from ' understanding '.

Delegate seems to be more used for asynchronous (begin invoke). The event is more used for custom events.

What is the relationship between delegate and async?

Asynchrony is a function that a delegate can implement (or it can be called a "phenomenon") that can be asynchronously expressed in many other ways, such as multithreading (Thread,threadpool,task, etc.).

Related Article

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.