Multithreaded Pipe Communication on Windows
Dec 28, 2014
A Pipe, which has two ends, is a section of shared memory that used for communication between processes. It allows processes to read and write information from each end. In this tutorial, I’d like to share how to build the pipe communication for multiple threads on Windows.
Pipi Communication between Two Threads in C#
Create a pipe instance:
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);
Wait for the client connection:
PipeCommunication.Pipe.ConnectNamedPipe(pipe, ref nativeOverlapped);
The client connects to the pipe server:
IntPtr pipe = PipeCommunication.Pipe.CreateFile(
PIPE_NAME,
(uint)(PipeCommunication.DesireMode.GENERIC_READ | PipeCommunication.DesireMode.GENERIC_WRITE),
0, IntPtr.Zero, 3, 128, IntPtr.Zero);
Write and read information between threads:
Server
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);
}
}
Client
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);
}
}
Source Code
https://github.com/DynamsoftRD/windows-pipe-communication
git clone https://github.com/DynamsoftRD/windows-pipe-communication.git