Asynchronous programming mode (APM) in. Net (1)

Source: Internet
Author: User
Tags apc apm net thread
ArticleDirectory
    • APM Introduction
    • Threadpool and computing-bound, I/O-bound operations

When I watched the Olympics some time ago, I suddenly got lazy and stopped updating. In the previous article, I was writing about XAML and extension. However, I recently reviewed the previous articles and thought it was necessary to summarize the asynchronous programming mode (APM) in. net ). The plan consists of four parts:
    • How to implement a class that supports APM
    • If you implement APM-supported hardware devices
    • Event-based APM
    • Continuation-Passing Style (CPS) APM
There are already many articles related to some content. The content I wrote is also mainly from the msdn concurrent affairs series. I mainly want to combine this content to see if we use the powerthreading class library to simplify our development.
Before starting, let's take a look at the asynchronous programming mode APM: APM introduction.

The concept of APM is simply that the main thread creates a thread to execute time-consuming tasks and continues to execute other tasks on its own. By using threadpool or thread, we can easily create a thread and let it execute the task. The difficulty lies in how the main thread knows whether the task is finished or not, and if it is canceled, control the execution of this task.

. Net 1. X defines the iasyncresult interface, and classes that execute time-consuming tasks in the class library provide both synchronous and asynchronous APIs, such as the filestream Method for synchronizing read files, corresponding asynchronous versions: beginread and endread. When the main thread calls the beginread method, this method immediately returns an iasyncresult object, and filestream starts to read the hard disk. Iasyncresult can be considered as a "handler" for this read operation, which is defined as follows:

1 Public   Interface Iasyncresult {
2 Waithandle asyncwaithandle { Get ;} // Used to wait until completion
3 Boolean iscompleted { Get ;} // Because of the Round-Robin viewing method
4 Object asyncstate { Get ;} // Used for callback
5 Boolean completedsynchronously { Get ;} // Almost never used again
6 }

With this "handler", we can wait for the task to end in three ways. From the interface definition, we can see the limitations of the iasyncresult method. After the main thread sends an asynchronous task, it cannot cancel the task or know the progress of the task. We will look at the following content to see if we can improve these problems.

In addition, beginxxx and endxxx must be called in pairs. beginxxx is used to trigger the execution of the task, and endxxx is used to obtain the return of the task execution. Although some tasks do not need to know the results, endxxx still needs to be called, otherwise it will cause memory leakage. If you can use the callback method, the more common method is to call endxxx In the callback function. Implementing callback functions is annoying. You must pass the filestream object through some methods, such as class member variables and asyncstate. Through the anonymous method and limbda in C #2.0, we can simplifyCodeIn the following example, the request local variables are passed to the callback function through the anonymous method partial variable capture function.

1 // C #2 anonymous Functions
2 VaR request = Httpwebrequest. Create ( " Http://www.google.com " );
3 VaR result = Request. begingetresponse (
4 Delegate (Iasyncresult Ar _)
5 {
6 VaR response = Request. endgetresponse (Ar _);
7 Processdata (response );
8 },
9 Null
10 );
11
12 // C #3 limbda
13 Result = Request. begingetresponse (
14 Ar _ => {
15 VaR response = Request. endgetresponse (Ar _);
16 Processdata (response );
17 },
18 Null
19 ); The threadpool and computing-bound, I/O-bound operations are just starting to look at CLR via C #, and they are not very familiar with the differences between computing-bound operation and IO-bound operation. Later, I realized it only by combining the. NET threadpool and the IO API and thread pool in the window.

First, we know that the threads in the. NET threadpool class are divided into worker thread and I/O thread. By default, the number of worker threads is * 25, and the number of I/O threads is 1000 .. Net threadpool is based on the thread pool provided by Windows OS. So let's take a look at the thread pool provided by windows.

Threads in Windows Thread Pool (before Vista) are also divided into two types: I/O worker thread and non-I/O worker thread. When we call a Windows API to perform synchronous read/write on I/O files, this thread creates an IRP device request and sends the IRP to the device stack, then wait for the core State to complete. When asynchronous mode is used, after the thread sends the IRP, it returns and continues subsequent operations. There are many ways for Windows to notify the completion of this I/O operation, and there are two types related to thread pool. One is to put the completed notification in the APC queue of the thread. The queue will be read only when the thread enters the waiting state; the other method is the I/O completion port. we can regard it as a queue, and read the queue through the getqueuedcompletionstatus API function. In Windows, thread pools are classified based on reading different queues. The I/O worker thread reads the APC queue, that is, when the thread completes a task, it enters the waiting state; the non-I/O worker thread reads the I/O completion port queue. Compared with the I/O completion port, APC has many problems and poor performance, but it still has to be supported for backward compatibility. Therefore, in. net, only the I/O completion port is encapsulated, that is, the I/O thread in. NET is used for non-I/O worker threads in windows. I hope I can stay awake. The I/O worker thread of APC does not have the. NET thread pool.

Therefore, in the. NET thread pool, the I/O thread is actually the I/O completion port, and the worker thread can be seen as a group of threads created in advance by the. NET Thread class .. Net and threadpool classes, such as queueuserworkitem, timer, and delegate callback, all use worker threads. The encapsulation of I/O operations in. net, such as filestream and networkstream, is the IO thread used.

Let's look back at the computing constraints computing-bound and I/O constraints I/O-bound operations mentioned in CLR via C. When we call filestream. beginread to read a file, beginread does not have a new thread to execute the read operation, the read operation (IRP) is executed by the device, and the thread continues to execute other tasks. When the device completes the read operation, a thread in the thread pool (IO thread) starts to execute the callback function.

When we execute the computing-bound operation, we start to create a new thread or use threadpool. queueuserworkitem uses the thread in the thread pool to perform operations. After the task is completed, the thread executes the callback function.

Through the above analysis, we can see that the actual different operation types, computing-bound vs I/O-bound, the implementation of the class library is different. Of course, we can also asynchronously computing-bound to synchronously call filestream. Read, but we do not use I/O to complete the high-performance port feature.

I would like to write this article. If we use powerthreading to implement APM, we should write it in the next article. I hope the above content will help you.

Refer:

CLR via C # chapter 23rd by Jeffery Richard dimplementing the CLR asynchronous programming modelsimplified APM with C # windows I/O threads vs. Managed I/O threads

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.