【发布时间】:2020-02-09 06:51:03
【问题描述】:
我目前正在尝试创建新的 NodeJS 进程,并在它运行时将其控制台输出放入我的 winform 文本框。
每当执行此进程时,它都会冻结主线程,就好像表单正在等待此进程退出一样。进程关闭后,控制台输出被添加到文本框。
我想要实现的是同时让这个节点进程在后台运行,并在文本框中输出它的任何内容。
编辑 1:
我设法在不冻结主线程的情况下运行控制台,但输出仅在进程关闭时显示
我当前的代码:
private void Btn_connect_Click(object sender, EventArgs e)
{
if(backgroundWorker1.IsBusy != true)
{
backgroundWorker1.RunWorkerAsync();
}
}
private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var worker = sender as BackgroundWorker;
nodeProcess = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "node.exe";
startInfo.Arguments = @"path" + " arg1 arg2 arg3";
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.RedirectStandardOutput = true;
nodeProcess.StartInfo = startInfo;
nodeProcess.Start();
while (worker.CancellationPending != true)
{
Thread.Sleep(200);
AddText(nodeProcess.StandardOutput.ReadToEnd());
worker.ReportProgress(1);
}
e.Cancel = true;
}
public void AddText(string text)
{
if(txt_log.InvokeRequired)
{
txt_log.Invoke(new Action<string>(AddText), new object[] { text });
return;
}
txt_log.Text += "\n " + text;
}
【问题讨论】:
标签: c# multithreading process backgroundworker