一個管道實際上就是一塊共享內存,它有兩端,分別用於兩個進程的讀寫。這裏介紹下如何在Windows上實現線程之間的管道通訊。html
參考原文:Multithreaded Pipe Communication on Windowsgit
建立一個管道實例:github
IntPtr pipe = PipeCommunication.Pipe.CreateNamedPipe( PIPE_NAME, (uint)PipeCommunication.PipeOpenModeFlags.PIPE_ACCESS_DUPLEX, (uint)(PipeCommunication.PipeModeFlags.PIPE_TYPE_BYTE | PipeCommunication.PipeModeFlags.PIPE_READMODE_BYTE), 1, 512, 512, 0, IntPtr.Zero);
等待客戶端鏈接:
c#
PipeCommunication.Pipe.ConnectNamedPipe(pipe, ref nativeOverlapped);
客戶端鏈接管道服務端:windows
IntPtr pipe = PipeCommunication.Pipe.CreateFile( PIPE_NAME, (uint)(PipeCommunication.DesireMode.GENERIC_READ | PipeCommunication.DesireMode.GENERIC_WRITE), 0, IntPtr.Zero, 3, 128, IntPtr.Zero);
線程之間讀寫數據:
多線程
服務端
app
PipeCommunication.Pipe.WriteFile(pipe, bytes, (uint)(sizeof(byte) * bytes.Length), bytesWrittenOrRed, ref nativeOverlapped); try { while (value < 10) { //omit to Clear bytes PipeCommunication.Pipe.ReadFile(pipe, bytes, (uint)(sizeof(byte) * bytes.Length), bytesWrittenOrRed, ref nativeOverlapped); value = BitConverter.ToInt32(bytes, 0); value++; bytes = BitConverter.GetBytes(value); Thread.Sleep(300); PipeCommunication.Pipe.WriteFile(pipe, bytes, (uint)(sizeof(byte) * bytes.Length), bytesWrittenOrRed, ref nativeOverlapped); } }
客戶端ui
try { while (value < 10) { //omit to Clear bytes PipeCommunication.Pipe.ReadFile(pipe, bytes, (uint)(sizeof(byte) * bytes.Length), bytesWrittenOrRed, ref nativeOverlapped); value = BitConverter.ToInt32(bytes, 0); value++; bytes = BitConverter.GetBytes(value); Thread.Sleep(300); PipeCommunication.Pipe.WriteFile(pipe, bytes, (uint)(sizeof(byte) * bytes.Length), bytesWrittenOrRed, ref nativeOverlapped); } }
https://github.com/DynamsoftRD/windows-pipe-communicationspa
git clone https://github.com/DynamsoftRD/windows-pipe-communication.git
Pipes線程