Preliminary understanding of Asynchronization

Source: Internet
Author: User
Tags apm

When I first tried multithreading, I found that multithreading can reduce or eliminate the stagnation caused by a large number of complicated operations or long waits (that is, thread blocking ). Later I found that the same effect can be achieved through asynchronous operations. However, there is a difference between the two. I have read some articles in the knowledge base before, And I have recorded some of them (people feel like clouds). By the way, I have some personal opinions.

Both multithreading and Asynchronization can reduce or eliminate the stagnation caused by thread blocking, but they are essentially different.

Multithreading is a software-level mechanism. At the micro level, it allocates the CPU time slice to each thread in a process. The thread that obtains the time slice can process its tasks, that is, execute code. The operating system is responsible for CPU resource scheduling. Therefore, whether multithreading can be implemented depends on the operating system. Most of the operating systems today are multi-threaded systems, and DOS does not support multithreading.

Asynchronous mode is a hardware-level mechanism. When studying Computer composition principles in universities, I mentioned hardware DMA (Direct Memory Access, Direct Memory Access ), it allows some computer external devices (NICs, disks, and so on) to directly interact with the memory to read and write data without consuming CPU time. During this period, the CPU can start other tasks, after I/O is completed, the scheduling permission is returned to the CPU. It can be seen that there is no need for the support of the operating system in the past, so follow this idea, if you only need the hardware support of the computer, asynchronous operations can also be implemented in DOS (I did not actually implement DOS as I saw on the Internet ).

From the above differences, we can infer their applicability. Asynchronization is on the hardware layer. Some operations on the hardware layer are suitable for asynchronous operations, such as file read/write operations, database Access, network access, etc.; multithreading is at the software level. Whether the CPU allocates time slice to the current thread is not related to whether external devices can directly access the memory, the same operation also consumes the same CPU time. In comparison, it is appropriate to use multiple threads to implement some operations that take a lot of CPU time to process.

In theory, as mentioned above, returning to the. NET Framework seems to be another thing. Run the following code:

           Main(              PrintThreadInfo(             Action act = () { PrintThreadInfo(             IAsyncResult ir = act.BeginInvoke(                                        PrintThreadInfo(             Action caller = result.AsyncState               PrintThreadInfo(               Console.WriteLine(.Format( ,Thread.CurrentThread.ManagedThreadId,Thread.CurrentThread.IsThreadPoolThread?:         }

 

 

It is found that asynchronous operations still use multithreading, and the newly opened thread comes from the ThreadPool of the thread pool. On MSDN, I found out that the BeginInvoke explanation is indeed asynchronous. It does belong to the APM mode (BeginXXX/EndXXX ). Next, let's take a look at how other classes work in the APM mode.

           Main(              PrintThreadInfo(             [] datas = Encoding.ASCII.GetBytes(             FileStream fs =  FileStream(, FileMode.Create, FileAccess.Write,FileShare.Write,              fs.BeginWrite(datas, , datas.Length,                              PrintThreadInfo(             FileStream caller = result.AsyncState             }

Here we have selected FileStream as an example, but from the results we can see that even though it is actually an asynchronous operation, it is indeed a file write, but there is still a thread pool called and a thread is used. Let's look back at the results of the first example. BeginInvoke and the callback method are both executed on the same thread, which has limitations compared to the second example, when BeginWrite is called, you cannot check whether a thread is used for write operations. The second line of information is displayed during callback. So is it the same as in the previous example that both run on the same thread? I have a poor method, as shown in

In the first example

In the second example

Although such a breakpoint test seems a little wrong, it is unconvincing. In contrast, we can see that in the first example, a thread is created when an asynchronous method is called, which is strictly not asynchronous. In the second example, no thread is created when an asynchronous method is called, the thread is not created until it is returned. It can be preliminarily confirmed that no thread is created when BeginWrite is called. The DMA mechanism is used, and it is actually an asynchronous call.

According to what Mr. Zhao said, CLR will send an IRP (I/O Request Packet) (via Windows API ). When the device is ready, it will find and process an IRP (for example, a request to read the data closest to the current head) that is "most desired, after the processing is completed, the device returns an IRP indicating that the work is completed (via Windows. CLR creates an IOCP (I/O Completion Port) for each process and maintains it with the Windows operating system. Once the completed IRP is put into the IOCP (completed through the internal ThreadPool. BindHandle), the CLR will allocate an available thread as soon as possible to continue the next task.

In my personal understanding, CLR interacts with the underlying hardware so that the corresponding device no longer consumes CPU to access the device. As mentioned in the theoretical section at the beginning of the article, Asynchronization is a hardware aspect. Therefore, some delegated asynchronous calls of inininvoke are false Asynchronization. For example, the asynchronous operations of the above files are true Asynchronization, the following methods can be used to implement true Asynchronization:

  • FileStream operations: BeginRead and BeginWrite (only the FileOptions. Asynchronous parameter is input when FileStream is constructed to obtain the true Asynchronous operation; otherwise, the operation is still false Asynchronous ).
  • DNS operation: BeginGetHostByName and BeginResolve.
  • Socket operations: BeginAccept, BeginConnect, and BeginReceive.
  • WebRequest: BeginGetRequestStream and BeginGetResponse.
  • SqlCommand operation: BeginExecuteReader, BeginExecuteNonQuery, and so on (set Asynchronous Processing to true in the connection string; otherwise, an exception is thrown when an Asynchronous method is called ).
  • WebServcie call operation: for example, the BeginXXX method in. NET 2.0 or the Web Service Proxy generated by WCF, And the InvokeAsync method of ClientBase <TChannel> In WCF.

The last record is that the callback method or EndXXX must be called when the APM mode is used. Otherwise, the thread resources cannot be recycled and the system may crash.

For more information about the above articles, see "correct use of asynchronous operations" by Dr. Zhao. For more information, see the following. If you think there are any mistakes, please criticize and correct them, let us talk about any suggestions or comments. Thank you!

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.