Twenty-eight chapters I / O limitations asynchronous operation

table of Contents

28.1 Windows how to perform I / O operations

28.2 C # asynchronous function

28.3 compiler how to convert asynchronous state machine function

28.4 asynchronous function scalability

28.5 asynchronous functions and event handlers

28.6 FCL asynchronous function

And exception handling function asynchronously 28.7

Other features 28.8 asynchronous function

28.9 threading model and its application

28.10 asynchronously achieve server

28.11 Cancel I / O operation

28.12 Some I / O operations must be synchronized

28.13 I / O request priority

Asynchronously perform I / O operations restrictions, allowing processing tasks into hardware devices, completely occupied during the threads and CPU resources.

28.1 Windows how to perform I / O operations

Synchronous I / O operations : program to open a disk file by constructing FIleStream object, and then calls the Read method of reading data from a file. When you call the Read method of the FileStream, your thread transition from managed code-based / user-mode code, internal call Win32ReadFile Read function. ReadFile assigned a small data structure, called the I / O request packet (IRP). After the contents comprising IRP structures are initialized: the offset file handle, the file (read bytes from the start position), a Byte [] data addresses (array of bytes read filled with), to be transmitted bytes of data and other conventional content. Then, ReadFile will change your thread from the machine / user-mode code to native / kernel-mode code, IRP data structure passed to the kernel which calls the Windows kernel. According to the device handle the IRP, Windows kernel knows I / O operations to be transferred to which hardware devices. Therefore, Windows IRP will be sent to the appropriate device driver IRP queue. Each device drivers maintainer own IRP queue that contains the I / O request to all processes running on the machine emitted. When the packet arrives at the IRP, the device driver information to the IPR circuit board mounted on a physical hardware device. Now, the hardware device to perform the requested I / O operation. During the hardware device to perform I / O operations, issued the I / O request thread will have nothing to do, so Windows will become the thread to sleep, to prevent it from CUP waste of time. Eventually, the device completes the hardware I / O operation. Then, Windows will wake your thread, it dispatched to a CPU, it returns to user mode from kernel mode, and then return to managed code. FileStream's Read method is now back in a Int32, indicate the actual number of bytes read from the file, so that you know to pass the Read Byte [], the actual number of bytes can be retrieved.

I / O asynchronous operation : construction FileSteam object, passing a FileOptions.Asynchronous identity, I would like to tell Windows file read / write operations in an asynchronous manner. ReadAsync call to read data from a file, it is assigned an internal Task <Int32> object to represent the code for the read operation is finished. Then call Win32ReadFile function. ReadFIle distribution IRP, and in front of the synchronous operation as initialize it, then pass it to the Windows kernel. Windows hard disk drive to add the IRP program IRP queue. But the thread is no longer blocked, but allowed to return to your code. ContinueWith callback method can be invoked to perform the registration task completion Task <Int32>, and processing data callback method. Hardware handle the IRP, the IRP will be completed into the CLR thread pool queue. Sometime in the future, a thread pool thread will complete the IRP to extract and execute the code to perform the task, and ultimately set either abnormal or return results.

Create a CLR at initialization I / O completion port . When you open the hardware devices that can be and I / O completion port, the device driver will know where to complete the IRP.

28.2 C # asynchronous function

The method of mark async, the compiler converts the code to implement a method of the type state machine. This allows thread execution state machine and return some code, does not require executed to completion.

Asynchronous function restrictions:

Main method can not speak of the application into asynchronous function. Further, constructors, properties, methods and events accessor accessor methods can not be converted to an asynchronous function.

Asynchronous or out function can not use any parameters ref.

Await operator can not be used in the catch, finally block or unsafe.

A thread can not obtain ownership or support recursive lock prior to await operator, and release it after the await operator. Use await in C # lock statement, the compiler will complain.

, The await operator can only be used in the first query expression from the initial clause set expression, the expression used in the aggregate or join clause.

28.3 compiler how to convert asynchronous state machine function

 When using await any operator, the compiler will get the number, and try to call GetAwaiter method on it. This may be an instance method or extension method. Call GetAwaiter method returns the object referred awaiter, it is the object wait state machine are bonded together.

After the state machine to get awaiter, queries its IsCompleted property. If the operation has been completed in a synchronous manner, property returns true, and one of the most optimization measures, the state machine will continue and calls GetResult method of awaiter. The methods are either throw an exception or return a result. If the operation is done asynchronously, IsCompleted returns false. The state machine call OnCompleted method awaiter of passing it a delegate (reference method MoveNext state machine). Now, the state machine allows it to return to their original threads to execute other code. Sometime in the future, it encapsulates the underlying task awaiter will be commissioned at the completion of calls to perform MoveNext. The state machine may be in the field knows how to reach the proper position in the code, a method from a position in which it had left to continue. In this case, the code calls awaiter of GetResult method. Execution will continue from here, in order to process the results.

28.4 asynchronous function scalability

 In terms of scalability, the Task object can package a future operation performed, the operator can use to await the waiting operation.

With a type (Task) to indicate asynchronous operation of the various coding advantageous, because it is possible (such as the Task WhenAsy WhenAll and methods), and other useful operations combining operation.

In addition to enhancing flexibility, asynchronous functions when using Task for another extension of the favorable place is that the compiler can call GetAwaiter on any number of operating await. So operand is not necessarily the Task object. It can be of any type, as long as the GetAwatier a method that can be called.

28.5 asynchronous functions and event handlers

 The return type is generally asynchronous function Task or Task <TResult>, they represent a function of the state machine is completed. But asynchronous function is returning void. When implementing asynchronous event handlers, C # compiler allows you to take advantage of this special situation simplifies coding.

Method Signature: void EventHandlerCallback (Object sender, EventArgs e);

28.6 FCL asynchronous function

Asynchronous function is easy to distinguish because the regulatory requirements for the additional Async method name suffix.

 System.IO.Stream of all derived classes provide ReadAsync, WriteAsync, FlushAsync and CopyToAsync method.

System.IO.TextReader of all derived classes provide ReadAsync, ReadLineAsynchronous, ReadToEndAsync and ReadBlockAsync method. System.IO.TextWriter derived class provides WriteAsync, WriteLineAsyc and FlushAsync method.

System.Net.Http.HttpClient class provides GetAsync, GetSteamAsync, GetByteArrayAsync, PostAsync, PutAsynchronous, DeleteAsync and many other methods.

System.Net.WebRequest all derived classes (including FileWebRequest, FtpWebRequest and the HttpWebRequest) GetRequestStreamAsync provides methods and GetRequestAsync

System.Data.SqlClient.SqlCommand class provides ExecuteDbDataReaderAsync, ExecuteNonQueryAsync, ExecuteReaderAsync, ExecuteScalarAsync ExecuteXmlReaderAsync and methods.

Generate a Web service proxy types of tools (such as SvcUtil.exe) method also generates XxxAsync

And exception handling function asynchronously 28.7

Windows device driver handles asynchronous I / O request may be wrong: the device driver has completed the post CLR thread pool of IRP. A thread pool thread will complete Task object and set exceptions. When you restore a state machine approach, await operator discovery operation fails and throws the exception.

If the state machine unhandled exception occurs, then the asynchronous functions on behalf of the Task objects to complete because of an unhandled exception. Then, waiting for the Task code will see an exception. But asynchronous function is also possible to use a void return type, this is no way to find the caller unhandled exception. Therefore, the return void asynchronous function throws an unhandled exception, the compiler generates code to capture it, and synchronize using the context of the caller to re-throws it. If the caller is performed by the GUI thread, GUI thread will eventually re-thrown. This exception is thrown again usually cause the entire process to terminate.

Other features 28.8 asynchronous function

VS provides excellent support for asynchronous function.

Asynchronous C # lambda expressions.

28.9 threading model and its application

 .Net Framework supports several different application models, and each model can introduce its own threading model. Console applications and Windows services (also the actual console application: console just can not see it) did not introduce any thread processing model; in other words, any thread can do anything it wants at any time.

But GUI applications (including Windows Forms, WPF, Silverlight and Windows Store application) introduces a threading model. In this model, UI elements can only be updated by the thread that created it.

ASP.NET application allows any thread to do anything it wants. When the thread pool thread starts processing a client's request, we can make assumptions about the language and culture of the client, allowing Web server numbers, date and time returned by the language and culture-specific formatting. In addition, Web servers but also on the client's identity assumption is made, to ensure that resources can only access the client has access to.

28.10 asynchronously achieve server

 To build asynchronous ASP.NET Web Form, add the Async = "true" page directive in the .aspx file, and reference System.Web.UI.Page of RegisterAsyncTask method.

To build asynchronous ASP.NET MVC controller, the controller of your class derived from System.Web.Mvc.AsyncController, allowing the operator method returns a Task <ActionResult> can be.

To build asynchronous ASP.NET handler, make your class derived from System.Web.HttpTaskAsyncHandler, override its abstract methods ProcessRequestAsync

To build asynchronous WCF service, will serve as an asynchronous function implementation, it returns a Task or Task <TResult>.

28.11 Cancel I / O operation

 WithCancellation implement a method to extend the Task <TResult>

28.12 Some I / O operations must be synchronized

 FCL can not open the file asynchronously, access to the registry, visit the event log for the file directory / subdirectory or change the attributes of files / directories, etc.

Windows Runtime asynchronous method allows to perform I / O operations. You can use the C # asynchronous function simplifies the encoding when calling the API.

28.13 I / O request priority

Windows allow the thread of the specified priority when issuing I / O request, the FCL does not include this feature can take the form of P / Invoke native Win32 function.

To call ThreadIO of BeginBackgrouondProcessing method, you tell Windows threads to issue low priority I / O requests. This will also reduce the CPU thread scheduling priority. Callable EndBackgroupProcessing, or on a call Dispose BeginBackgroundProcessing return value, so that the thread is sent to restore normal priority I / O requests (ordinary CPU scheduling priority). Thread can only affect its own background processing mode; Windows thread is not allowed to change a background thread processing mode.

If you want all threads in a process of issuing low-priority I / O requests and low-priority CPU scheduling, call BeginBackgroundProcessing, passing true value to its Process parameters, a process can only affect its own background processing mode; Windows does not allow one thread to change the background processing mode to another process.

 

Guess you like

Origin www.cnblogs.com/terry-1/p/11198677.html