Negative tive C # Principle 21: delegate a callback)

Source: Internet
Author: User

Valid C # Principle 21: Delegate the callback

Item 21: Express callbacks with delegates

Me: "Son, weed in the yard. I want to read books ."
SCOTT: "Dad, I have cleaned the yard ."
SCOTT: "Dad, I have already put the grass on the render server ."
SCOTT: "Dad, the host cannot be started ."
Me: "Let me start it ."
SCOTT: "Dad, I'm done ."

This simple interaction shows the callback. I gave my son a task and he could report the status to interrupt me. While I am waiting for him to complete every part of the task, I don't have to block my own process. He can interrupt me regularly when reporting important (or event) status, or ask me for help. Callback is used to asynchronously provide information feedback between the server and the customer. They may be in multiple threads or simply provide a synchronous update point. In C #, the callback is represented by a delegate.

The delegate provides a type-safe callback definition. Although most delegates are used for events, this function should not be the only place in C. At any time, if you want to communicate between two classes, and you want to have less coupling than using interfaces, then delegate is your right choice. Delegation allows you to run the confirmation (callback) Target and notify the user. A delegate is a reference that contains some methods. These methods can be static or instance methods. With delegation, you can determine to interact with one or more customer objects at runtime.

Multicast delegates include all single function calls added to this delegate. There are two points to note: it is not exceptionally safe, and the return value is always the value returned after the last function call.

Each target is successfully called within the multicast delegate call. The delegate does not capture any exceptions. That is to say, any exceptions thrown in the delegate chain will terminate the continuing call of the delegate chain.

There is also a simple problem with the return value. You can define whether the delegate has a return value or a void. You may write a callback function to detect abnormal user interruptions:

Public Delegate bool continueprocessing ();

Public void lengthyoperation (continueprocessing Pred)
{
Foreach (complicatedclass CL in _ container)
{
Cl. dolengthyoperation ();
// Check for user ABORT:
If (false = PRED ())
Return;
}
}

This is a task on a single Commission, but there is a problem with the multicast Commission:
Continueprocessing CP = new continueprocessing (
Checkwithuser );
CP + = new continueprocessing (checkwithsystem );
C. lengthyoperation (CP );

The value returned from the delegate call is actually the value returned from the call of the last function. All other return values are ignored. That is, the assertions returned from checkwithuser () are ignored.

You can manually set two delegates to call two functions. Each delegate you create contains a delegate chain. Directly detect this delegate chain and call each delegate by yourself:

Public Delegate bool continueprocessing ();

Public void lengthyoperation (continueprocessing Pred)
{
Bool bcontinue = true;
Foreach (complicatedclass CL in _ container)
{
Cl. dolengthyoperation ();
Foreach (continueprocessing PR in
Pred. getinvocationlist ())

Bcontinue & = Pr ();

If (false = bcontinue)
Return;
}
}

Now, I have definedProgramTherefore, each delegate on the delegate chain must return true before calling.

The delegate provides the best method for callback during runtime. You can easily implement your requirements for classes. You can determine the purpose of the delegate at runtime. You can support multiple user targets. In this way, the user callback can be implemented using the delegate in. net.
========================================

Item 21: Express callbacks with delegates
Me: "Son, go mow the yard. I'm going to read for a while ."

SCOTT: "Dad, I cleaned up the yard ."

SCOTT: "Dad, I put gas in the mower ."

SCOTT: "Dad, the mower won't start ."

Me: "I'll start it ."

SCOTT: "Dad, I'm done ."

This little exchange has strates callbacks. I gave my son a task, and he (repeatedly) interrupted me with the status. I did not block my own progress while I waited for him to finish each part of the task. he was able to interrupt me periodically when he had an important (or even unimportant) status to report or needed my balance ance. callbacks are used to provide feedback from a server to a client asynchronously. they might involve multithreading, or they might simply provide an entry point for Synchronous updates. callbacks are expressed using delegates in the C # language.

Delegates provide type-safe callback definitions. although the most common use of delegates is events, that shoshould not be theonly time you use this language feature. any time you need to configure the communication between classes and you desire less coupling than you get from interfaces, a delegate is the right choice. delegates let you configure the target at runtime and configure y multiple clients. A delegate is an object that contains a reference to a method. that method can be either a static method or an instance method. using the delegate, you can communicate with one or multiple client objects, configured at runtime.

Multicast delegates wrapall the functions that have been added to the delegate in a single function call. two caveats apply to this construct: it is not safe in the face of statements, and the return value will be the return value of the last function invocation.

Inside a multicast delegate invocation, each target is called in succession. The delegate does not catch any exceptions. Therefore, any exception that the target throws ends the delegate invocation chain.

A similar problem exists with return values. You can define delegates that have return types other than void. You cocould write a callback to check for user aborts:

Public Delegate bool continueprocessing ();

Public void lengthyoperation (continueprocessing Pred)
{
Foreach (complicatedclass CL in _ container)
{
Cl. dolengthyoperation ();
// Check for user ABORT:
If (false = PRED ())
Return;
}
}

 

It works as a single delegate, but using it as a multicast is problematic:

Continueprocessing CP = new continueprocessing (
Checkwithuser );
CP + = new continueprocessing (checkwithsystem );
C. lengthyoperation (CP );

 

The value returned from invoking the delegate is the return value from the last function in the multicast chain. All other return values are ignored. The return from the checkwithuser () predicate is ignored.

You address both issues by invoking each delegate target yourself. Each delegate you create contains a list of delegates. To examine the chain yourself and call each one, iterate the invocation list yourself:

Public Delegate bool continueprocessing ();

Public void lengthyoperation (continueprocessing Pred)
{
Bool bcontinue = true;
Foreach (complicatedclass CL in _ container)
{
Cl. dolengthyoperation ();
Foreach (continueprocessing PR in
Pred. getinvocationlist ())

Bcontinue & = Pr ();

If (false = bcontinue)
Return;
}
}

 

In this case, I 've defined the semantics so that each delegate must be true for the iteration to continue.

Delegates provide the best way to utilize callbacks at runtime, with Simpler requirements on client classes. you can configure delegate targets at runtime. you can support multiple client targets. client callbacks shocould be implemented using delegates in. net.


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.