开发者

C# Keeping Pipes Open

开发者 https://www.devze.com 2022-12-10 23:48 出处:网络
I\'ve Got two Programs (Server / Client) I\'m trying to setup IPC for them (They both run on the same box)

I've Got two Programs (Server / Client) I'm trying to setup IPC for them (They both run on the same box) Using System.IO.Pipes & Net 3.5

When I call ComOpen, it opens the Pipe correctly, sends the Process ID to the server, but then the Pipe closes and I get an error when it tries to send "Second Write Test"

So Question is. How do I keep the Pipe open for the Life of the Program? (I use the Process ID on the server to close everything down if the Client crashes)

private static StreamWriter MyWriter;
private static StreamReader MyReader;
private static NamedPipeClientStream IPCPipe = new NamedPipeClientStream(".", "MyPipe", PipeDirection.InOut);


    public static bool MyWrite(string DataOut)
    {
        bool ValidPipeOut = false;
        if(ValidComPort)
        try
        {
            // Send Data
            using (QstWriter = new StreamWriter(IPCPipe))
            {
            开发者_运维技巧    QstWriter.AutoFlush = true;
                QstWriter.WriteLine(QstDataOut);
                QstWriter.Close();
                QstWriter.Dispose();
            }
            ValidPipeOut = true;
        }
        catch
        {
            ValidPipeOut = false;
        }
        return ValidPipeOut;
    }


    public static bool ComOpen()
    {
        ValidComPort = true;

        try { IPCPipe.Connect(1000); }
        catch (Exception ex)
        {
            string Erroris;
            Erroris = ex.Message;
            if (Erroris == "Already in a connected state.")
            {
                // We're Already Connected, Ignore this error.
                ValidComPort = true;
            }
            else
            {
                ValidComPort = false;
                MessageBox.Show(Erroris);
            }
        }
        if (ValidComPort)
        {
            string ClientProcessID = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
            MyReader = new StreamReader(IPCPipe);
            ValidComPort = MyWrite(ClientProcessID);
            ValidComPort = MyWrite("Second Write Test");
        }
        return ValidComPort;
    }


The problem is the following line:

using (QstWriter = new StreamWriter(IPCPipe))

At the end of the using statement, the StreamWriter will be disposed and that will in turn dispose the IPCPipe. You are also explicitly calling Dispose and Close on QstWriter, which will close the pipe too.

To fix this, remove the using statement and the calls to Dispose and Close on QstWriter. And assign+initialize QstWriter only once.

0

精彩评论

暂无评论...
验证码 换一张
取 消