简体   繁体   中英

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

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, ie 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!

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.

当您向服务器发送信号以检查更新时,请在BackgroundWorker类中进行操作

The solution to this problem turned out to be a matter of rethinking the design of the software.

Instead of having a UserControl that talks to a seperate application each step of the Update process, the UserControl handles it all itself and then finally when it needs to apply the update (which involves overwriting application files, hence the need for a seperate process in the first place) it simply uses Process.Start("...") along with some command line arguements to call a seperate process to finish the job.

A much simpler solution than trying to do Inter-Process Communication for this task.

Still, it would have been nice to find out why my Bi-Directional communication wasn't working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM