C # pipes open

I have two programs (server / client) I'm trying to configure IPC for them (they both work in the same window) Using System.IO.Pipes and Net 3.5

When I call ComOpen, it correctly opens the handset, sends the process identifier to the server, but then the panel closes, and I get an error message when I try to send a "Test of the second record"

So there is a question. How to keep a tube open for life of the program? (I use the process identifier on the server to close everything if the client fails)

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;
    }
+3
source share
1 answer

The problem is the following line:

using (QstWriter = new StreamWriter(IPCPipe))

using StreamWriter , , IPCPipe. Dispose Close QstWriter, .

, using Dispose Close QstWriter. + QstWriter .

+1

Source: https://habr.com/ru/post/1722627/


All Articles