首页 > 代码库 > 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上的多线程管道通信