一个管道实际上就是一块共享内存,它有两端,分别用于两个进程的读写。这里介绍下如何在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线程