首页 > 代码库 > Windows上的多线程管道通信
Windows上的多线程管道通信
一个管道实际上就是一块共享内存,它有两端,分别用于两个进程的读写。这里介绍下如何在Windows上实现线程之间的管道通信。
参考原文:Multithreaded Pipe Communication on Windows
C#多线程管道通信
创建一个管道实例:
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);
等待客户端连接:
PipeCommunication.Pipe.ConnectNamedPipe(pipe, ref nativeOverlapped);
客户端连接管道服务端:
IntPtr pipe = PipeCommunication.Pipe.CreateFile( PIPE_NAME, (uint)(PipeCommunication.DesireMode.GENERIC_READ | PipeCommunication.DesireMode.GENERIC_WRITE), 0, IntPtr.Zero, 3, 128, IntPtr.Zero);
线程之间读写数据:
服务端
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); } }
客户端
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-communication
git clone https://github.com/DynamsoftRD/windows-pipe-communication.git
参考
Pipes
Windows上的多线程管道通信
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。