C#我需要在单独的线程上读取stdout吗?

时间:2019-03-14 19:23:53

标签: c# redirect process stdout stdin

在C#中,我试图运行一个命令行程序,该程序从stdin获取输入,然后将输出返回到stdout。我需要保持cmd.exe运行(使用/ k)并在for循环中,发送文本,然后等待输出,然后再发送下一个文本。如果我不重定向标准输出,但在重定向后不起作用,则此方法有效。最初,我从stdout取回了数据(尽管要晚得多了),现在除了启动程序的初始调用之外,该数据不再起作用。 link这样说:“或者,您可以通过创建两个线程并在单独的线程上读取每个流的输出来避免死锁情况。” 这样可以解决我的问题,如果可以,我将如何解决?

代码设置如下:

StringBuilde  sb = new StringBuilder();
    Process process = new Process();
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.WorkingDirectory = workingdirectory;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.FileName = "cmd.exe";
        process.StartInfo.Arguments = "/k";
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardInput = true;    
        process.EnableRaisingEvents = true;
        process.OutputDataReceived += (sender, args) => AppendData(args.Data); //this appends the output to a stringbuilder
        process.ErrorDataReceived += (sender, args) => AppendError(args.Data);

    process.Start();  

        //sw is a streamwriter
        sw= process.StandardInput;

    //now call the command line code 
        sw.WriteLine(" some.exe some.arg ");

    process.BeginOutputReadLine();

        foreach(DataRow row in dtMydata.Rows)
    {   
        mytext=row["Text"].toString();

        sw.WriteLine(mytext);  
        sw.WriteLine(Environment.NewLine); //This redirects the text to the program,

    }

0 个答案:

没有答案