如何保持PipeSteam开放?

时间:2015-07-17 12:01:32

标签: c# multithreading pipe

我需要保持PipeStrem打开而不是关闭它,即摆脱使用。我试图让它保持打开状态,但得到Exception Cannot Access closed strem 我该如何解决?这是我现在的代码:

    public static void StartServer()
    {

        //NamedPipeServerStream pipeStream = new NamedPipeServerStream("PipeTo" + Process.GetCurrentProcess().Id.ToString());

        while(true)
        {
            using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("PipeTo" + Process.GetCurrentProcess().Id.ToString()))
            {

                Console.WriteLine("[Server] Pipe Created, the current process ID is {0};\n[Server] The current process name is {1}", Process.GetCurrentProcess().Id.ToString(), Process.GetCurrentProcess().ProcessName);
                try { pipeStream.WaitForConnection(); }
                catch
                {
                    _worker = new BackgroundWorker();
                    _worker.DoWork += _worker_DoWork;
                }
                Console.WriteLine("[Server] Connected Successfully");

                using (StreamReader sr = new StreamReader(pipeStream))
                {                        
                    string pathToExe = string.Empty;

                    while ((pathToExe = sr.ReadLine()) != null)
                    {
                        Process.Start(pathToExe);                            
                    }
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

using关于流本身, StreamReader会导致其关闭。

有关详细信息:Does disposing streamreader close the stream?