Callbacks for C # methods (ON)

Source: Internet
Author: User

There are several ways to callback methods in C # programming:

asynchronous callbacks through interfaces , through delegates , timed callbacks , multi-threaded callbacks

This is explained in code form below.

callback via Interface

Code examples such as the following

defines an interface that defines a run method :

Interface icallback{    void  Run ();}

Define the class that implements the interface and implement the method defined in the interface, which is the function of outputting the current time:

class callbackclass:icallback{    publicvoid  Run ()    {        Console.WriteLine ( DateTime.Now);}    }

Defines the control callback class, which defines a field of an interface type that is used to reference the callback object. Defines a Byinterface method for executing callbacks:

classcontroller{//Interface Callbacks    Private ReadOnlyIcallback _callbackobject =NULL;  PublicController (Icallback obj) { This. _callbackobject =obj; }     Public voidByinterface () {Console.WriteLine ("tap any key to display the current time, ESC key to exit ...");  while(Console.readkey (true). Key! =consolekey.escape) { This. _callbackobject.run (); }    }}

In the main method, execute:

Static int Main (string[] args) {    new Controller (new  callbackclass ());    Controller. Byinterface ();     return 0 ;      }

Execution Result:

Tap any key to display the current time, ESC key to exit ...

2015/08/10 16:03:22
2015/08/10 16:03:22
2015/08/10 16:03:23
2015/08/10 16:03:23
2015/08/10 16:03:23

What do you think about the use of Icallback interface variables in the controller class?

I think that in the control callback with the interface type to do the field, it will undoubtedly reduce the coupling between classes and classes, not confined to a particular class, as long as the implementation of the interface object can be called, such a program is advocated.

implementing callbacks through Delegates

Control the callback class code

classcontroller{//Define a field for a delegate type    PrivateAction ShowTime =NULL;
Receive external methods within a constructor PublicController (Action showTime) { This. showTime + =ShowTime; } Public voidBydelegate () {Console.WriteLine ("tap any key to display the current time, ESC key to exit ..."); while(Console.readkey (true). Key! =consolekey.escape) { This. ShowTime (); } }}

In the main method, execute:

Static int Main (string[] args) {   new Controller (new Action () =   Console.WriteLine (DateTime.Now));   Controller. Bydelegate (); }

The result is the same as an example of an interface callback, where results are not shown here

The red word in the above code is an anonymous method written by the lambda expression;

Because delegates allow dynamic addition (+ =) and remove (=) callback methods, they are more flexible to use than interfaces.

through timed callbacks

This way the scenario is special and requires a method to be called at regular intervals.

The timer class provided by the. NET framework is used to periodically callback a method that satisfies the requirements of the TimerCallback delegate, which is defined as follows:

 Public Delegate void TimerCallback (object State);

The delegate defines a method for an object type parameter. The Timer class constructor is as follows:

 Public Object int int period)

Parameter resolution:

Callback: Method of timing callback

State: Parameters passed to the callback method

Duetime: The time, in seconds, to delay before developing a callback method. Set to 0 to invoke callback method immediately

Period: Number of seconds between execution of the callback method

Examples are as follows:

 Public classtaskinfo{ Public intCount =0;}Static classprogram{Static voidMain () {varTi=NewTaskInfo (); varTM =NewTimer ( obj = = {var TaskInfo = obj as TaskInfo; taskinfo.count++;                                Console.WriteLine (Taskinfo.count); } , Ti,0, +);           Console.readkey (); Tm.        Dispose (); }}    

In the code above, the red Word is an anonymous function, and a lambda expression is used.

About multi-threaded callbacks and asynchronous callbacks the next chapter continues ~ Thank you

Callbacks for C # methods (ON)

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.