问题
I have a simple WPF application that communicates with another console program. I use Process.Diagnostic to launch the console app. That console app has a prompt so I can send the input through StandardInput and read the outcome through StandardOutput.
I want to launch the console application only once (keep it alive whole time) when the WPF apps loads and keep sending input and reads the output.
I have some piece of code but I don’t how to put it all together.
The problem is that after sending the input I want to wait until the prompt occurs before I start reading the output line by line so I have entire outcome. I know I can check if the process is waiting for input like that:
foreach (ProcessThread thread in _proccess.Threads)
{
if (thread.ThreadState == System.Diagnostics.ThreadState.Wait
&& thread.WaitReason == ThreadWaitReason.UserRequest)
{
_isPrompt = true;
}
}
But where should I put that code to check if the ThreadState has changed? In a separate thread and how to do that?
I hope that someone can put some light on that issue. Thanks in advance.
回答1:
In a WPF app you can use the System.Windows.Threading.DispatcherTimer.
Example adapted from MSDN documentation:
// code assumes dispatcherTimer, _process and _isPrompt are declared on the WFP form
this.dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
this.dispatcherTimer.Tick += (sender, e) =>
{
this._isPrompt = proc
.Threads
.Cast<ProcessThread>()
.Any(t => t.WaitReason == ThreadWaitReason.UserRequest);
};
this.dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
this.dispatcherTimer.Start();
...
this._process.Start();
来源:https://stackoverflow.com/questions/8978512/process-diagnostic-waiting-for-user-input