C # multithreaded Tour (4) A tentative study of--APM

Source: Internet
Author: User
Tags apm class definition

Original address: C # multithreaded Tour (4)--APM

C # multithreaded Tour directory:

C # multithreaded Tour (1)--Introduction and basic concepts

C # multithreaded Tour (2)--Create and start threads

C # multithreaded Tour (3)--thread pool

C # multithreaded Tour (4) A tentative study of--APM

C # multithreaded Tour (5)--Introduction to the synchronization mechanism

C # multithreaded Tour (6)--A detailed description of locks in multiple threads

More articles are being updated, so please look forward to ...

C # multithreaded Tour (4) A tentative study of--APM

v Blog Preface

First of all, the background, the previous several main content is to introduce the basic knowledge of multithreading, this chapter is due to the APM (asynchronous programming model), found that APM is really powerful, some of the knowledge points involved in the delegation of the Begininvoke/endinvoke, Sincerely want to write about APM knowledge.

v written in front

Powerful asynchronous processing model, have to be impressed by it!

v Body StartA simple serial execution programLet's start by looking at a simple procedure: define a int Add (int num)The number of times that the loop was passed NUM, which returns the sum of the results of the loop addition. Step 1.Main method calls the Add method, the loop executes 2 times, so delay 2s, return the result sum=1, print result:1; The Step 2.Main method loops 3 times and delays 3s.Friendly Reminder: If you don't want to read the colorful ConsoleTo print the code, you can choose to see the collapsed code area below. Check out the simple version of code that prints out colors

Let's look at the running results of this program:

we can see from the results:1. Execute the Add method, which is the main thread to execute the Add method; 2. The main thread executes the main method; 3. This time-limited operation can be referred to as "asynchronous operation to compute the limit"; 4. In the Add method, which simulates time-consuming operations (2s) and the main method in which the simulated time-consuming operation (3s) is executed serially, do we have a way to make both operations run in parallel? (The two time-consuming operations are done within 3s). The answer is that you can use APM. below we use APM method to save 2s of time. Second, the use of the delegation to achieve APM2.1 preparatory knowledge we use generic delegates to implement APM, then we need a bit of preliminary knowledge (to the delegates are skilled students can skip the preparatory knowledge): 1. What is a delegate?  2. What is a generic delegate? 3. Why use delegates to implement APM? For this knowledge point 1, 2, you can refer to the blog I wrote earlier, here is no longer explained, not afraid of the interview: Delegate for the third point of knowledge, because the delegate defines two async methods BeginInvokeAnd EndInvoke。 We can first look at the definition of a generic delegate:
<summary>///defines a generic delegate///</summary>///<typeparam name= "T" > Input Parameters </typeparam>///< Typeparam name= "TResult" > Return value </typeparam>///<param name= "arg" > Input parameters </param>///<returns name = "TResult" > Return value </returns>private delegate TResult func<t, tresult> (T Arg);

For this definition, the C # compiler compiles this line of code into a class definition with the following logical definition:

Public sealed class Func<t, tresult>: Multicastdelegate{public Func (Object obj, IntPtr method);p ublic TResult Invok E (t Arg);p ublic IAsyncResult BeginInvoke (t Arg, AsyncCallback callback, Object obj);p ublic TResult EndInvoke ( IAsyncResult result);}

When a delegate is defined, a class of BeginInvoke and EndInvoke methods is generated.

When you define the following delegate

public delegate void MyDelegate (int value);

To view the results by Ilspy the anti-compilation tool:

BeginInvoke:

1. The first parameter, ARG, defines the same parameters for the delegate (which can be the same as the two parameter arg, and the delegate's signature), which can be passed to the delegate reference method;

2. The second-to-last parameter callback is the callback method, and when the BeginInvoke method finishes executing, the callback method is called immediately, and if Callback=null, the callback method is not invoked;

3. The first parameter of the Countdown object is used for EndInvoke.

4. The return value is an interface object of type IAsyncResult (actually an instance of type Asynresult). Purpose of the interface object

A. Pass the parameter, which contains a reference to the delegate that called BeginInvoke, which is the input parameter of the int type of the Add method;

B. A parameter containing the last object type of BeginInvoke ()

C. It can identify which method is called, because the same delegate variable can be called multiple times on the same method.

EndInvoke:

1. The first parameter receives the Iansyresult returned by the BeginInvoke;

2. The returned TResult is the return value of the delegate-referenced method, which is the int type return value of the Add method

2.2 How to implement APM with delegates

2.3 Write a code that implements APM

Through the above flow chart, I believe that we have a certain understanding of the implementation of APM, and then read code, I believe that can be faster to understand. Comments for reference only, there are questions can reply to me Oh!

Let's look at the results:

Attention:

1. The IAsyncResult must be converted to asyncresult before it can get to the referenced delegate because it is not included in the definition of the IAsyncResult interface;

2.Add method calls, the Addcallback method is called by thread pool threads;

The 3.BeginInvoke object parameter can be of any type, with the arguments "I ' m here!" passed in the example of a string type ;

4. For loop and Add method executed by the main thread the thread is simultaneous, and the result is alternately printed;

5. When the async Add method does not complete, calling EndInvoke will block the current thread pool threads, and only the code will continue to execute after the Async method has finished executing;

After the 6.Add method executes, the callback method Addcallback is called automatically;

7. The call to EndInvoke may throw an exception, so you need to add try/catch/finally to catch EndInvoke's possible exception.

v written in the last

Because it's just beginning to get into the knowledge of APM, this article is just about writing a discussion, and later chapters will cover more of that. hope to get the support of the Friends of the park!

C # multithreaded Tour (4) A tentative study of--APM

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.