CLR非異步操做讀取文件的過程圖web
非異步操做主要是由於每次請求硬件如(硬盤,網卡等)的線程都處於阻塞狀態,致使之後的請求都須要從新建立新的線程。致使線程上下文的切換頻繁。異步
異步IO操做主要是經過每次的請求完硬件創造好IRP,線程就會返回到線程池中,未來硬件完成任務時,會主動去線程池中找線程來繼續完成的操做。這樣返回到線程池的線程就能夠去作本身的事情了。函數
能夠使用一個去本市旅遊乘車的例子來講明:this
能夠請一班車,送到旅遊地方,車該去哪裏去哪裏,回去的時間給公交公司打電話,來一輛車,這樣不用讓來的那個車在旅遊地點一直等着,形成資源的浪費。spa
下面是使用IO異步操做的一個實例線程
{ m_pipe.BeginRead(data, 0, data.Length, GotRequest, data); } private void GotRequest(IAsyncResult result) { // The client sent us a request, process it. Int32 bytesRead = m_pipe.EndRead(result); Byte[] data = (Byte[])result.AsyncState; // My sample server just changes all the characters to uppercase // But, you can replace this code with any compute-bound operation data = Encoding.UTF8.GetBytes( Encoding.UTF8.GetString(data, 0, bytesRead).ToUpper().ToCharArray()); // Asynchronously send the response back to the client m_pipe.BeginWrite(data, 0, data.Length, WriteDone, null); }
注意end****方法都是出如今Begin****中的回調函數中。code
通常只須要在End裏面去捕捉就ok了。下面演示一個例子server
public static void Go() { WebRequest webRequest = WebRequest.Create("http://0.0.0.0/"); webRequest.BeginGetResponse(ProcessWebResponse, webRequest); Console.ReadLine(); } private static void ProcessWebResponse(IAsyncResult result) { WebRequest webRequest = (WebRequest)result.AsyncState; WebResponse webResponse = null; try { webResponse = webRequest.EndGetResponse(result); Console.WriteLine("Content length: " + webResponse.ContentLength); } catch (WebException we) { Console.WriteLine(we.GetType() + ": " + we.Message); } finally { if (webResponse != null) webResponse.Close(); } }