I have an application that is polling for data every 20ms, processing the data and creating individual messages and each message is then sent one by one to another application via a pipe.
Now when I have lots of data, sending the data to the pipe takes a lot of time because for each message sent to the pipe, the pipe connection is opened then closed. Using Stopwatch I have found that processing the data takes less than a millisec on its own, but when the data is sent via the pipe the time can take between 2 to 13 millisecs. Below is the send function:
public bool Send(byte[] SendStr, string PipeName, int TimeOut)
{
bool status = false;
try
{
NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", PipeName, PipeDirection.Out, PipeOptions.Asynchronous);
pipeStream.Connect(TimeOut);
Debug.WriteLine("[Client] Pipe connection established");
message = "Pipe connection established";
status = true;
pipeStream.BeginWrite(SendStr, 0, SendStr.Length, AsyncSend, pipeStream);
}
catch (TimeoutException oEX)
{
Debug.WriteLine(oEX.Message);
message = "Pipe connection Error: " + oEX.Message;
}
return status;
}
private void AsyncSend(IAsyncResult iar)
{
try
{
NamedPipeClientStream pipeStream = (NamedPipeClientStream)iar.AsyncState;
pipeStream.EndWrite(iar);
pipeStream.Flush();
pipeStream.Close();
pipeStream.Dispose();
}
catch (Exception oEX)
{
Debug.WriteLine(oEX.Message);
message = "Pipe Error: " + oEX.Message;
}
}
I can speed this up by just combining all the data messages together and doing one send ie just one pipe send during the processing rather than multipes pipe sends.
This solves my timing problem.
But is it possible to open the pipe connection at the start of the program then send data messages whenever I want to the pipe before closing the pipe when exiting the program ( Similar to writing to a file)? I have tried to do this but get errors such as pipe not open when I try to send the second message.
Or is it necessary to open/close the pipe connection at every write?
What I have tried:
I have searched online and not found anything relevant. If it is possible to open a pipe connection and send multiple messages before closing the pipe connection, a link or example of how to do it would be appreciated.
ie is it necessay to open/close connection each time data is sent? Or can I keep it open until the program ends?