16

私はc#のコマンドラインを使用してプログラムを実行しています。このプログラムはいくつかのログを生成しますが、実行中は変更が発生するたびにこのログを表示する必要があります。次のコードを記述しましたが、プロセスが強制終了され、実行中にプログラムが応答しなくなると、すべてのログが表示されます。どうすれば修正できますか?

よろしく

ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + "C:\\server.py");
Process proc = new Process();
procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
procStartInfo.UseShellExecute = false;
procStartInfo.RedirectStandardOutput = true;
//procStartInfo.CreateNoWindow = true;
proc.StartInfo = procStartInfo;
proc.Start();
string output = proc.StandardOutput.ReadToEnd();
proc.WaitForExit(300);
LogstextBox.Text = output;

編集済み: まあ、使用しようとしましOutputDataReceivedたが、結果が表示されません。変更されたコードは次のとおりです。

{
            //processCaller.FileName = @"ping";
            //processCaller.Arguments = "4.2.2.4 -t"; this is working
            processCaller.FileName = @"cmd.exe";
            processCaller.Arguments = "/c c:\\server.py"; //this is not working
            processCaller.StdErrReceived += new DataReceivedHandler(writeStreamInfo);
            processCaller.StdOutReceived += new DataReceivedHandler(writeStreamInfo);
            processCaller.Completed += new EventHandler(processCompletedOrCanceled);
            processCaller.Cancelled += new EventHandler(processCompletedOrCanceled);
            this.richTextBox1.Text = "Server Started.." + Environment.NewLine;
            processCaller.Start();
    }

    private void writeStreamInfo(object sender, DataReceivedEventArgs e)
    {
        this.richTextBox1.AppendText(e.Text + Environment.NewLine);
    }
4

2 に答える 2

22

これが問題です:

string output = proc.StandardOutput.ReadToEnd();

プロセスが終了するまで、標準出力の「終わり」に到達することはありません。

一度に1行ずつ読む必要があります。または、イベントをサブスクライブするだけでよいOutputDataReceived(そして、そのイベントについて文書化されている他の要件に従う)必要があります。

編集:これが私のために働くサンプルコードです:

using System;
using System.Diagnostics;
using System.Threading;

class Program
{
    public static void Main()
    {
        ProcessStartInfo startInfo = new ProcessStartInfo("cmd", "/c " + "type Test.cs")
        {
            WindowStyle = ProcessWindowStyle.Hidden,
            UseShellExecute = false,
            RedirectStandardOutput = true,
            CreateNoWindow = true
        };

        Process process = Process.Start(startInfo);
        process.OutputDataReceived += (sender, e) => Console.WriteLine(e.Data);
        process.BeginOutputReadLine();
        process.WaitForExit();
        // We may not have received all the events yet!
        Thread.Sleep(5000);
    }
}

サンプルコードでは、ハンドラーが呼び出されるスレッドでUIにアクセスしていることに注意してください。これは、OutputDataReceived私には悪い考えのように見えます。

于 2012-10-01T17:56:28.383 に答える
3

Process.BeginOutputReadLineメソッドを使用できます。このリンクは、を使用するC#での完全な動作例を示していますOutputDataReceived event。そのコード例はあなたが望むことをするはずです。

于 2012-10-01T18:00:31.310 に答える