在等待进程结束时显示消息

时间:2013-07-11 18:13:11

标签: c# console-application progress waitforexit

我有一个控制台应用程序启动一个过程(大约需要2-3个小时才能完成)

有没有办法可以显示一条消息“进程正在运行...”每隔几分钟,下面是代码:

            using (process)
            {
                var output = new StringBuilder();
                var error = new StringBuilder();

                using (var outputWaitHandle = new AutoResetEvent(false))
                using (var errorWaitHandle = new AutoResetEvent(false))
                {
                    process.OutputDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                        {
                            outputWaitHandle.Set();
                        }
                        else
                        {
                            output.AppendLine(e.Data);
                        }
                    };
                    process.ErrorDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                        {
                            errorWaitHandle.Set();
                        }
                        else
                        {
                            error.AppendLine(e.Data);
                        }
                    };

                    process.Start();
                    Console.WriteLine("Process is running..."); // THIS ONLY DISPLAYS ONCE

                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();
                    process.WaitForExit();
                    Console.WriteLine("Process has shutdown...")    

                }

1 个答案:

答案 0 :(得分:1)

您的进程正在占用主线程,因此在进程运行时您将无法在该线程上执行任何操作。创建一个Background Worker,使用计时器偶尔输出到控制台。