【发布时间】:2019-10-08 06:15:26
【问题描述】:
一旦我启动进程,空白(无文本)控制台窗口就可见,但它似乎没有发出命令。
这是我如何定义我的流程:
void Init()
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "CMD.exe";
// psi.FileName = @"cmd.exe";
// psi.Arguments = @"'/K' C:\Dev\Anaconda3\Scripts\activate.bat C:\Dev\Anaconda3";
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
// psi.WorkingDirectory = @"C:\temp";
psi.UseShellExecute = false;
// psi.CreateNoWindow = true;
// psi.WindowStyle = ProcessWindowStyle.Hidden;
process = Process.Start( psi );
process.ErrorDataReceived += ( sender, e ) =>
{
if( ErrorDataReceived != null )
{
ErrorDataReceived.Invoke( e.Data );
}
};
process.OutputDataReceived += ( sender, e ) =>
{
if( OutputDataReceived != null )
{
OutputDataReceived.Invoke( e.Data );
}
};
}
启动线程
Thread thread;
Process process;
public void Start()
{
Init();
thread = new Thread(ThreadMain);
thread.Start();
}
注册外部命令以执行
string command;
bool command_complete = true;
public void Exec( string command )
{
if( ! command_complete ) return;
this.command = command;
command_complete = string.IsNullOrWhiteSpace( command );
}
我的活动:
public event Action<string> ErrorDataReceived;
public event Action<string> OutputDataReceived;
public event Action<string> InputDataReceived;
她我可以看到 InputDataReceived 从外部被调用,但从来没有 OutputDataReceived
void ThreadMain()
{
while( true )
{
if( exit ) break;
if( ! command_complete )
{
process.StandardInput.WriteLine( command );
if( InputDataReceived != null )
{
InputDataReceived.Invoke( command );
}
command_complete = true;
}
Thread.Sleep( 250 );
}
Dispose();
}
【问题讨论】:
标签: c# windows multithreading terminal process