创建并积极使用Process而不冻结主线程

时间:2019-10-11 18:03:17

标签: c# multithreading process backgroundworker

我目前正在尝试创建新的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;
        }

1 个答案:

答案 0 :(得分:1)

您可以尝试使用Process.BeginOutputReadLineProcess.OutputDataReceivedProcess.Exited代替Unable to fetch auth token. Error: HTTPSConnectionPool(host='login.microsoftonline.com', port=443): Max retries exceeded with url: /common/oauth2/v2.0/token (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])")))

BackgroundWorker