C# – How To Asynchronously Read/Write A Named Pipe In C#

cnamed-pipes

I have a Windows form which hosts a custom User Control. This User Control fires up a seperate process (a .exe) which creates and initializes a NamedPipeServerStream. Once the process initializes the NamedPipeServerStream, the User Control connects to it as a NamedPipeClientStream.

This all works fine.

On the Windows form I then have a button called "Check For Updates". When this button is pressed, the NamedPipeClientStream sends a message to the server, to which the server responds which a MessageBox saying "I've been told to check for updates". So I can tell this client > server communication is working fine.

Here's the problem. The server is then supposed to send a message BACK to the client telling it that it's now checking for updates (So the User Control can update its status after verying its command was received by the server). But whenever this happens, everything locks up.

Now I am going to assume that this is because I am attempting to both read AND write to the Named Pipe at the same time?

Below are some code snippets from both the Server and the Client. (Both these snippets run in seperate threads in their respective processes so as to not block the UI)

GUpdater (The Named Pipe Server):

private void WaitForClientCommands()
{
    // Wait for a connection from a Named Pipe Client (The GUpControl)
    pipeStream.WaitForConnection();
    pipeConnected = true;

    // Create a StreamWriter/StreamReader so we can write/read to the Named Pipe
    pipeStreamWriter = new StreamWriter(pipeStream) { AutoFlush = true };
    pipeStreamReader = new StreamReader(pipeStream);

    // Now that we have a connection, start reading in messages and processing them
    while (true)
    {
        // Skip this time if we are currently writing to the pipe
        if(isWritingToPipe) continue;

        var message = pipeStreamReader.ReadLine();
        if (message == null)
        {
            // We don't want to hog up all the CPU time, so if no message was reaceived this time, wait for half a second
            Thread.Sleep(500);
            continue;
        }

        switch(message)
        {
            case "CheckForUpdates":
                //MessageBox.Show("Told to check for updates");
                SendMessageToClient("Checking For Updates, Woot!");
                break;
            case "DownloadUpdate":
                MessageBox.Show("Told to download update");
                break;
            case "ApplyUpdate":
                MessageBox.Show("Told to apply update");
                break;
        }
    }
}

GUpControl (The Named Pipe Client):

private void WaitForServerCommands()
{
    if(!pipeConnected) return;

    // Now that we have a connection, start reading in messages and processing them
    while (true)
    {
        // Skip this time if we are currently writing to the pipe
        if (isWritingToPipe) continue;

        // Attempt to read a line from the pipe
        var message = pipeStreamReader.ReadLine();
        if (message == null)
        {
            // We don't want to hog up all the CPU time, so if no message was reaceived this time, wait for half a second
            Thread.Sleep(500);
            continue;
        }

        MessageBox.Show("I got a message from the server!!\r\n" + message);
    }
}

The following snippet is the method that is responsible for writing to the Client/Server from each component. (The only difference is in the name, i.e. SendMessageToClient and SendMessageToServer)

private void SendMessageToServer(string message)
{
    if(pipeConnected)
    {
        isWritingToPipe = true;
        pipeStreamWriter.WriteLine(message);
        isWritingToPipe = false;
    }
}

The isWritingToPipe variable is a simple bool that is true when the respective process is attempting to write to the Named Pipe. This was my initial attempt at solving the problem.

Any help is much appreciated!

Best Answer

System.IO.Pipes.PipeStream has a method WaitForPipeDrain() which is the correct way to manage coordination between the client and server when exchanging messages.

The TransmissionMode for the pipe may also be affecting things: are you using Byte mode or Message mode? I'm not sure how well wrapping the stream in a StreamReader plays with the pipe message mode semantics, for example. See this SO answer for more on message mode.