The post-reading thinking of Mr. Zhang Ziyang's two articles on the Commission and the events (well-spoken, with a story)

Source: Internet
Author: User

First delegate and event in C # Second delegate and event in C # (cont.)

First of all, Mr. Zhang Ziyang's two article on the relationship between delegates and events, is the most concise and clear article I've read about delegates and events and asynchronous invocations, and the author's structure of "How to", "thinking", "the idea", "the topic" , step by step to the implementation of the Commission and the event, the application and the principle is very clear, and during the writing of their own interesting thinking process through vivid language to express, make people read more and more interested in, the following is I read these two articles, on the Commission, events, asynchronous invocation of some new understanding of the interpretation of the angle.

(Recommended Mr. Zhang Ziyang's article link at the beginning of this article, you can completely not read my story, first to see those two articles, really very fun) First, you should quote a summary from the author's text:
A
delegate is a class that defines a method's type so that it can be passed as a parameter to another method, which dynamically assigns the method to the parameter, avoids the large use of the If-else (Switch) statement in the program, and makes the program more extensible.
I think this sentence can be from the concept of Clr-via design to explain my understanding:The function of the concept of delegation is to implement the observer pattern, and define the type of the method with the name of the class in the encapsulation, which represents the same method of a class of parameter list. Yes, that 's right, that is, the various names of the same parameter list method, has the ability to classify the batch processing capacity of the package, after the collation can be easily labeled delegate this keyword has a specific parameter list of the method marked as a class, and at all did a subscription operation (+ = ) is placed in a list<t> of the proxy class generated after its compilation, then, at the time of invocation, it is simple to use an instance member of the call delegate to pass the parameter list defined by the proxy once. Call this set of same-type methods that subscribe to this delegate instance, because they need the same list of parameters. So what's the matter with C # delegation? first tell a story, the legend of a city (program area), the protagonist of the story is You (main thread), the town has 100 craftsmen (with the subscription function can subscribe to the class), Each of these 100 people can use a specific material and tools to make their best work (the same parameter list), this time, you find that these tools and materials have channels to find, so, you think if the material into a work, how much market ah, in the businessman's profit-oriented thinking, You have announced that these craftsmen can ask you for materials and tools to make his own work (initial project requirements).  So, you start to find a way to prepare the selected materials and tools , which is defined in the parameter list of the delegate type, so you need to do a business name for this matter, you can be abstracted as a type of delegate, a name is called Delegate Sendtoolandmaterial (tools,material) okay. you know exactly what kind of tools and materials you're looking for, and you're looking for a stock channel, so you can start going out there. You can collect materials and tools for the people you need, and you can come to collect them, and the thing that you open the news is to define a member of your class. Delegate instance (public sendtoolandmaterial sendtoolmaterial;) and then, outside you get this message (see Common Members sendtoolmaterial), Then someone tells you he wants your tool material, because he can do the work of this material, the behavior is that the subscription operation "+ =", in fact, when the compile run, the subscription function is added to the list of delegates. Delegate Invocationafter you have sent a tool and material (it is possible that a person did not send it), at this time because you did not say when the craftsmen to complete, so any one who knows you hair tools and materials, can ask you to see the goods (call your delegate instance), You have to bring back the work of the artist that you used to send the tools and materials, and then decide whether to buy it or not. So you see the business come ~, just excited to look for you before looking for tools and materials of the craftsmen to work (execute the Subscription function list). because it is a synchronous call, so you (the main thread) can only one person, find a will let this receive materials and tools to start the production, and so he finished, and then go to the next person to receive goods, so you get all the work of the time spent is all the craftsmen to make the work of the sum of time, It is possible that the customer has been waiting for the time-out, it is possible that you have previously sent the works of these craftsmen do not meet his requirements, but you only sent these few people, so there are a few single you spent time goods also pressed in your hand, good sad urge ~ but still become a few single profit small money. At this time, you feel that the finished product is insufficient, can not meet all the visitors to see the aesthetic needs of the guests, you think there should be a plan to take the goods, and then start to make the guests look at the goods, so that you can sell the most works, so you began to calculate ... the relationship between event event and delegate delegate in C #The story continues, or this can send tools and materials of you, or the city, experienced the above to receive the work of this matter, you feel that any person who knows you can come to ask you to interrupt your own work to get the works (Implementation of the delegation) this is very uncomfortable (in fact, the collection of works is very time-consuming, This also makes the customer very dissatisfied, but you do not realize that there is an urgent need for improvement, so you decided not to let outsiders have the right to ask you, so you said to the outside, although I distributed tools and raw materials, but I only in the public display, we can only come to the visit transaction (event to the internal encapsulation of the delegate). since it's an internal decision-making plan, it doesn't matter when people say they want to visit, so you encapsulate the delegate (delegate)of the previous tool material as an event, and the distribution tool becomes ready to be released . (External definition is public event), but when to collect the work of the matter will become your own decision -making (the compilation will become private), to see you in the mood, maybe you think hair 50 can take a lap, maybe the raw material is insufficient, You can only send 30 people to take a lap, depending on which node you want to execute this list of delegates, so you can use the artisan or raw material every time completely.  So, the principle of the event is actually the delegate, in the programming time can also fully use the delegate to implement the subscription and bulk call, but the event will be the delegate encapsulated into the internal invocation characteristics (as to how the event calls how to define, and compiled into what code, you can go to those two articles in the United States, I only tell the story ~).  due to the application of internal events, no one bothered you to distribute the task, so slowly you feel that this is really very slow ah ..., 100 people I want next to each other, this is not a silly leak? Moreover, others halfway looking for me to ask for something, I also ignore him ah, I (main thread) is still outside next to receive things, this is not angry to run the guests only blame. No, I have to change my business. after encountering a problem, you begin to think, so the concept of asynchronous execution is born thinking it through, when you're done, tell them ( myevent.getinvocationlist ()) to start working together (BeginInvoke (toolobj, meterailobj, NULL, NULL), do I have to collect my work (IAsyncResult ) ? Even if I do not put the tools and materials are all finished, who led the thing who started, I gave him a courier phone, finished to me handed over ? (So you feed The courier industry here)? At this time he started, who came to me and asked me to wait for him to finish the work for me (IAsyncResult asyncResult = Del. BeginInvoke (2,5,null,null); So I can continue to do my own thing while they're working (the main thread task), even if I want to make a deal in the middle, I'm going to rush a specific person to give me his work (EndInvoke (asyncResult), And then I can do something else, and then nobody stops working (thread pool (Thread.CurrentThread.IsThreadPoolThread)), how efficient!  so you start, using this new business strategy, you have to change the concept of business, a material outward, the works are led by the craftsmen began to create, or in a courier, or in the meeting of customers to do transactions, high efficiency, sound meaning is more and more prosperous, busy very much Ah!   asynchronous callbacks and asynchronous calls to incoming dataThe story goes on. After a good deal of business, you find yourself already familiar with the market, but also have a certain taste of art, so you are wondering how to get these craftsmen to take back material tools, can follow their own meaning to get the work, so you start to think about each distribution of tools and materials at the same time to give the craftsmen some topics and other information, This makes the best use of the artisan resources at hand, allowing more work to be done in line with current market expectations. So you do it, every time you send a tool in the craftsman says you can start to dry ((BeginInvoke (null, eventargs.empty, NULL, NULL)) , you have a good time, big blow your present inspiration, How I wish to achieve an effect this is the art of the cattle, and then you let the craftsmen deeply infected, according to your thoughts and feelings (string data = "Any data want to pass.";) To create a work. Because it's what you mean, you'll have the right to modify your work after you've done it (asynccallback callBack = new AsyncCallback (onaddcomplete);) Extra Money (parameter processing time overhead) to the craftsman. So the craftsman's original mode of creation changed, abruptly into your meaning, after the production you can also modify the work (Del. BeginInvoke (Toolobj,meterailobj, CallBack, data);).  after gaining a high level of CPU thread concurrency and the right to modify results freely, you are quite proud of this new mode of work, and have been happy to start putting all your ideas into production, frantically entering personalized advice for the original co-workers (super-diverse incoming parameters), And often criticize the craftsmen who cannot handle your opinion, think that they do not work, after getting the work of a lot of changes (write a lot of derivative callback function for matching demand) ... Benefits of AsynchronyI think the biggest advantage of Asynchrony is that the main thread can do the same thing as the protagonist who does business in the story, grasping the resources available in the thread pool to execute in time (the top two articles have explained in detail what a situation is, and it is very easy to understand, I do not have to explain the superfluous), Then the process, the results and the control of the results are all passed through the IAsyncResult returned by BeginInvoke, the incoming parameter AsyncCallback and the data parameters passed in, which makes the single-line wait task become the concurrent thread task. It's good to encapsulate the implementation of a set of thread collaboration. Finally, I made a happy ending for the story:For a long time, the craftsmen have followed your meaning, and the things that you have done have been modified according to your own aesthetics, and you are increasingly addicted to the high efficiency and self-fulfillment of the pleasure, because each time you need to pay a large sum of money to the craftsmen, and the more difficult the theme of the more expensive, resulting in significant cost growth ( Changing the parameter type of the parameters to generate the subscription parameter modification cost and additional business callback cost, and because the opponent is a variety of huchui various poach competition (more of the same kind of asynchronous calls), the market changes quickly, and because you have money to learn bad, go to the place of the feasting, Mouth to boast about the processing power of their business and their own artistic appreciation (think that server performance is enough to start blindly expanding business, resulting in a single node performance bottleneck), the reputation gradually become worse, rich people buy your things feel a little plunges, so buy people also less, invest less than output, Soon your own industry is down (the decline in service capability, which leads to service abandonment), replaced by a merchant group with a better reputation for better business practices (careful expansion of the business, continuous improvement of the architecture eventually spawned a distributed service architecture).

The post-reading thinking of Mr. Zhang Ziyang's two articles on the Commission and the events (well-spoken, with a story)

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.