代码之家  ›  专栏  ›  技术社区  ›  We Are All Monica

C-如何在进程退出时关闭标准输入和输出流?

  •  0
  • We Are All Monica  · 技术社区  · 15 年前

    我有一个进程需要启动一个子进程,并通过标准的输入和输出与它进行通信。子进程应该能够自动终止自己;但是,我无法正确关闭流。

    下面是来自child/“client”进程的相关代码:

    // This is started in a separate thread
    private void watchStandardInput() {
        string line = null;
        do {
            try {
                line = Console.ReadLine();
            } catch (IOException) {
                return;
            }
            lock (inputWatcher) {
                switch (line) {
                    // process command
                }
            }
        } while (line != null);
    }
    
    // This is called from the main thread
    private void updateStatus(string statusMessage) {
        lock (inputWatcher) {
            Console.WriteLine(statusMessage);
        }
    }
    

    下面是“服务器”代码:

    // This is in the main thread
    using (StreamReader sr = process.StandardOutput) {
        while (!process.HasExited) {
            processOutput(sr.ReadLine());
        }
    }
    
    // Finally, commands are sent in a separate thread.
    

    现在,对于我遇到的问题:当子进程应该退出时,服务器将保持在 sr.ReadLine() 客户停留在 Console.ReadLine() . 我做错什么了?

    1 回复  |  直到 15 年前
        1
  •  1
  •   Joel Rondeau    15 年前

    确保执行readline()的客户机线程的isbackground设置为true。不要在此线程上执行abort()/join()。只需关闭所有非后台线程。我发现,即使将isbackground设置为true,在后台线程上执行abort()/join()也会导致测试应用程序等待输入,但是,删除abort()/join()并定期退出仍然可以正常工作。

    推荐文章