[英]C# process thread can't write output
启动该过程后,空白(无文本)控制台窗口将可见,但似乎没有发出命令。
这是我定义流程的方式:
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();
}
刚看了这篇帖子 ,好像我忘了开始输入监控
void ThreadMain()
{
process.BeginOutputReadLine();
process.BeginErrorReadLine();
while( true )
{
// ...
Thread.Sleep( 250 );
}
process.CancelOutputRead();
process.CancelErrorRead();
Dispose();
}
尝试这个
if (!command_complete)
{
using (StreamWriter si = process.StandardInput)
{
si.WriteLine(command);
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.