异步控制台输出到文本块

时间:2011-06-20 08:12:13

标签: c# wpf

我想用一些参数执行一个可执行文件。

我希望我的WPF应用程序输出控制台行并以异步方式显示在文本块中。

这就是我到目前为止所做的:

System.Threading.Thread.Sleep(5000);
System.Diagnostics.Process runantc = new System.Diagnostics.Process();
runantc.StartInfo.FileName = "CMD.EXE";
runantc.StartInfo.Arguments = "/C " + Antcbatchpath;
runantc.StartInfo.UseShellExecute = false;

runantc.StartInfo.RedirectStandardOutput = true;
runantc.StartInfo.RedirectStandardError = true;

runantc.OutputDataReceived +=new DataReceivedEventHandler(runantc_OutputDataReceived);

runantc.Start();

runantc.BeginOutputReadLine();

runantc.Close(); 

private static void runantc_OutputDataReceived (object sendingProcess, 
DataReceivedEventArgs outLine)
{
 //i am not sure what should be here
}

上述代码根据msdn的webpage

进行了更改

我在跟踪代码时遇到了很多麻烦,因为他们需要添加字符串或某种类型。我是活动处理和此类流程的初学者。请帮助我,我只需要将这些行异步输出到文本块。

例如,控制台将输出:

running test...

我应该在textblock中看到:

running test...

然后几秒后出现另一条线:

running test...
this is a new line 1

以上几秒后也应出现在文本块中:

running test...
this is a new line 1

2 个答案:

答案 0 :(得分:1)

以下代码应该执行您想要的操作:

private static void runantc_OutputDataReceived (object sendingProcess, DataReceivedEventArgs outLine)
{
    YourControl.Dispatcher.BeginInvoke(new Action(() => { YourControl.Text += outLine.Data; }), null);
}

编辑:好吧,好像我必须稍微解释一下代码:

Dispatcher.BeginInvoke函数需要委托作为回调和参数数组。

答案 1 :(得分:0)

我不确定它是否会按照您的预期显示,但您可以使用DataReceivedEventArgs.Data属性从输出文本中获取详细信息。

相关问题