1. 程式人生 > >異步函數Demo

異步函數Demo

必須 wait 字節 sre pes connected 設置 count nec

 1         private static async Task<String> IssueClientRequestAsync(string serverName, string message)
 2         {
 3             Console.WriteLine("進入IssueClientRequestAsync");
 4             //NamedPipeClientStream 公開 System.IO.Stream 周圍命名管道,支持同步和異步讀取和寫入操作。
 5             //新實例初始化 System.IO.Pipes.NamedPipeClientStream 使用指定的管道和服務器名稱,以及指定的管道方向和管道選項的類。
6 // 參數: 7 // serverName: 8 // 要連接的遠程計算機的名稱,或者為“.”,以指定本地計算機。 9 // 10 // pipeName: 11 // 管道的名稱。 12 // 13 // direction: 14 // 確定管道方向的枚舉值之一。(此處指定的管道方向是雙向的) 15 // 16 // options:
17 // 確定如何打開或創建管道的枚舉值之一。 18 using (var pipe = new NamedPipeClientStream(serverName, "PipeName", PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.WriteThrough)) 19 { 20 Console.WriteLine("Connect"); 21 //連接到具有無限超時值的等待的服務器。
22 //必須在設置ReadMode之前連接 23 pipe.Connect(); 24 25 Console.WriteLine("ReadMode"); 26 //對象的讀取模式 27 //指示是發送和讀取的 消息流 的形式在管道中的數據,另外還有字節流(Byte) 28 pipe.ReadMode = PipeTransmissionMode.Message; 29 30 Console.WriteLine("request"); 31 byte[] request = Encoding.UTF8.GetBytes(message); 32 33 Console.WriteLine("WriteAsync"); 34 //將字節序列異步寫入當前流,並將流的當前位置提升寫入的字節數。 35 // buffer: 36 // 從中寫入數據的緩沖區。 37 // 38 // offset: 39 // buffer 中的從零開始的字節偏移量,從此處開始將字節復制到該流。 40 // 41 // count: 42 // 最多寫入的字節數。 43 await pipe.WriteAsync(request, 0, request.Length); 44 45 Console.WriteLine("response"); 46 byte[] response = new byte[1000]; 47 48 Console.WriteLine("ReadAsync"); 49 //從當前流異步讀取字節序列,並將流中的位置提升讀取的字節數。 50 // buffer: 51 // 數據寫入的緩沖區。 52 // 53 // offset: 54 // buffer 中的字節偏移量,從該偏移量開始寫入從流中讀取的數據。 55 // 56 // count: 57 // 最多讀取的字節數。 58 int bytesRead = await pipe.ReadAsync(response, 0, response.Length); 59 60 Console.WriteLine("retuen"); 61 return Encoding.UTF8.GetString(response, 0, bytesRead); 62 } 63 } 64 65 private static void NamedPipeClientStreamTest() 66 { 67 using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "testpipe", PipeDirection.In)) 68 { 69 70 // Connect to the pipe or wait until the pipe is available. 71 Console.Write("Attempting to connect to pipe..."); 72 pipeClient.Connect(); 73 74 Console.WriteLine("Connected to pipe."); 75 Console.WriteLine("There are currently {0} pipe server instances open.", pipeClient.NumberOfServerInstances); 76 using (StreamReader sr = new StreamReader(pipeClient)) 77 { 78 // Display the read text to the console 79 string temp; 80 while ((temp = sr.ReadLine()) != null) 81 { 82 Console.WriteLine("Received from server: {0}", temp); 83 } 84 } 85 } 86 }

異步函數Demo