Reading notes-clr via C # thread 27 Chapter

Source: Internet
Author: User
Tags apm readfile switches

Objective

This book in the past few years fragmented read two or three times, as a classic book, should repeat read and reread, since I began to write Bo, I am also ready to think of the classic good book reread carefully read it again, and put the notes into the blog, good memory than bad writing, but also in the process can deepen their understanding of the depth, And, of course, sharing it with friends from the technology community.

Synchronous IO execution process, take read example
    • Managed code into local user-mode code, read internally calls Win32 's ReadFile function
    • ReadFile allocation IRP (IO Request Packet)
    • IRP includes: one file handle, file offset, byte[] Array
    • IO requests into Windows kernel mode, passes the IRP, invokes the kernel, and according to the device handle, the kernel will distribute the IRP to the device-driven IRP queue
    • The thread is blocked in the IRP queue, the hardware executes IO and does not involve any threads
    • Threads become sleep, saving CPU time, but still wasting space (user-mode stack, kernel-mode stack, TEB, etc.)
    • The hardware device completes the Io,windows wakeup thread and dispatches it to a CPU
    • Thread returns user mode from kernel mode and returns managed code
The dangers of synchronous IO
    • Reduce server responsiveness and throughput
    • Wasting too much system resources (threads and memory)
    • Frequent context Switches
    • Thread pool frequently creates more new threads, blocking threads waking up with context switches
Asynchronous IO

The difference between asynchronous IO is that the IRP request is not blocked until the kernel mode is added to the IRP queue of the hard disk driver, but instead allows the return code, and the thread returns immediately. The delegate to the callback method invocation actually passes the channel device driver in the IRP. After the hardware has processed the IRP, the delegate for the IRP is placed in the CLR's thread pool queue. Thread pool threads extract the completed IRP and invoke the callback method. When the BeginXxx method is called, it constructs an object to uniquely identify the IO request, joins the request to the Windows Device driver queue, and then returns a reference to the IAsyncResult. The internal CLR thread pool uses IOCP to complete the binding and sending of asynchronous requests

Benefits of Asynchronous IO
    • Reduce resource utilization
    • Reduce context Switching
    • Boost GC performance and debug performance
    • Increase concurrency and throughput
Apm

Some classes that provide the begin and end method interfaces, but do not communicate with hardware devices, the code of these methods simply performs the operation of calculation restrictions. Cannot perform IO-restricted operations, so a thread is required to perform these operations

There are other in FLC: File stream class, network stream class, database class, Webservice, WCF

Based on the traditional begin...,end ... The asynchronous implementation of the pattern, if the implementation is based on IOCP, then it does not block on the IO thread. It is implemented by converting an IO request into an IRP (IO requests package) and then passing it to the hardware device-driven IRP queue, calling begin. The line of the method routines is returned immediately, and then the hardware driver goes to its IRP queue to take out the work item execution and does not use any threads when it is actually executed. When the implementation is finished, the IRP will be thrown up to the IOCP, and then thrown to Threadpool,threadpool will choose an IO thread to perform the BEGIN ... callback method passed in the method

The delegate's BeginInvoke method internally calls ThreadPool.QueueUserWorkItem to add a compute throttling operation to the thread pool queue of the CLR. It is best to return IAsyncResult to the caller.
If there is a callback, the thread pool threads do not return to the pool after execution, and the callback is invoked

Not recommended:

    • Calling end directly will block the
    • To avoid using the IAsyncResult WaitHandle property, you block the thread and may cause the thread pool to allocate another thread
    • Query iscompleted, also not recommended, will waste CPU events

Suggestions

    • Always calls end and is called only once. (1. Release Resources 2. Handling Exceptions)
    • The object that should be the same as the Begin method when the end method is called
Abnormal

When a begin throw exception is called, the asynchronous operation does not enter the queue, so thread pool threads do not invoke any callback methods passed to begin. The device driver posts the completed IRP to the CLR thread pool and puts an error code in the IAsyncResult that represents the asynchronous operation. The thread pool invokes the callback method, passing result, and the callback method passes result to the appropriate end method, and the end method finds that the error code converts it to the appropriate exception exception

General concerns about exceptions thrown from the end method call

If you call a method that does not return a value asynchronously by using a delegate, you do not know if there is an exception thrown when you do not call EndInvoke.

Delegate Async

An asynchronous invocation of a delegate is performed by a worker thread that hands the task to the thread pool.

The asynchronous implementation of the delegate BeginInvoke is run in a thread in the ThreadPool, but it is implemented based on the remoting architecture. This is obviously very cost-performance, so it's best not to use it

Thread Context Switch

The Context.post method sends callbacks to the GUI thread queue, allows the thread pool threads to return immediately, and send callbacks to the GUI thread queue, but then blocks thread pool threads, but then blocks the thread pool thread, knowing that the GUI thread is completing the call to the callback method. Note that these context calls the BeginInvoke (Post) or Invoke method internally. AsyncOperationManager is still used in EAP.

Eap

It is more convenient to use, but it is developed by the Wiondows form team, mainly for the use of WinForm, can be well used in WinForm development, but it will produce EventArgs objects on each departure, will cause a lot of rubbish. Second, the use of time to notify the outside is also a performance loss, the call to delegate than the virtual method to invoke performance is worse

EAP has many limitations, while implementing both modes. The EAP-enabled class automatically maps the application model to its threading model. The SynchronizationContext class was used internally

BackgroundWorker This component is still done by delegate BeginInvoke (can be viewed through reflector), so it is not recommended.

BackgroundWorker is used to perform asynchronous computation restrictions. Work that is not used to perform IO throttling

EAP compared to APM's disadvantage, 1: Packaging loss 2: Actual subscription Easy Memory Release 3. Error handling inconsistent

APM vs. Task conversion
    • IAsyncResult APM is converted to task through task.factory.fromasync<response>. Ask implements the IAsyncResult interface, which is compatible with APM. The task encapsulates the call to the End method
    • Convert EAP to task, created for TaskCompletionSource in event callbacks for EAP
Asynchronous programming model for the. NET Framework

Conclusion

I know, Jeffrey ritchter the chapter of the thread took a lot of effort, but the writing is still not very well summed up, such as he used 25 chapters on threading Foundation and thread development and historical background, this OK is understandable, but 26 chapters and 27 chapters obviously is a little disorganized, His title in Chapter 26 is to compute the limit of asynchrony, the thread pool then jumps directly to the part of the TPL (by the way, the timer), and the 27 chapter title is IO-constrained async, but actually speaking APM and EAP. Hey, so I read the book notes also write very messy, do not blame, just as a record of their own!

Reading notes-clr via C # thread 27 Chapter

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.