添加progressBar以查看c#中进程的进度百分比

时间:2013-02-12 21:52:37

标签: c# process progress-bar

这是关于我的流程的代码:

StreamReader outputReader = null;
StreamReader errorReader = null;


       ProcessStartInfo processStartInfo = new ProcessStartInfo(......);
       processStartInfo.ErrorDialog = false;

       //Execute the process
        Process process = new Process();
        process.StartInfo = processStartInfo;
        bool processStarted = process.Start();

                     if (processStarted)
                        {
                        //Get the output stream
                        outputReader = process.StandardOutput;
                        errorReader = process.StandardError;


                        //Display the result
                        string displayText = "Output" + Environment.NewLine + "==============" + Environment.NewLine;
                        displayText += outputReader.ReadToEnd();
                        displayText += Environment.NewLine + Environment.NewLine + "==============" +
                                       Environment.NewLine;
                        displayText += errorReader.ReadToEnd();
                        // txtResult.Text = displayText;
                    }

我需要将progressBar添加到我的表单中以计算此过程的进度百分比,但我不知道该怎么做。

我正在使用Visual Studio 2012,Windows窗体。

2 个答案:

答案 0 :(得分:3)

使用流程OutputDataReceived事件来捕获进度。 (假设该过程提供任何类型的更新)。您可以格式化初始输出以返回总增量数,然后对每个输出事件进行提升或实际解析输出数据以确定当前进度。

在此示例中,流程的输出将设置最大值,并且每个后续步骤都会将其提升。

e.g。

progressBar1.Style = ProgressBarStyle.Continuous;
// for every line written to stdOut, raise a progress event
int result = SpawnProcessSynchronous(fileName, args, out placeholder, false,
    (sender, eventArgs) =>
    {
        if (eventArgs.Data.StartsWith("TotalSteps=")
        {
          progressBar1.Minimum = 0;
          progressBar1.Maximum = Convert.ToInt32(eventArgs.Data.Replace("TotalSteps=",""));
          progressBar1.Value = 0;
        }
        else
        {
          progressBar1.Increment(1);
        }
    });


public static int SpawnProcessSynchronous(string fileName, string args, out string stdOut, bool isVisible, DataReceivedEventHandler OutputDataReceivedDelegate)
{
    int returnValue = 0;
    var processInfo = new ProcessStartInfo();
    stdOut = "";
    processInfo.FileName = fileName;
    processInfo.WorkingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? "";
    log.Debug("Set working directory to: {0}", processInfo.WorkingDirectory);

    processInfo.WindowStyle = isVisible ? ProcessWindowStyle.Normal : ProcessWindowStyle.Hidden;
    processInfo.UseShellExecute = false;
    processInfo.RedirectStandardOutput = true;
    processInfo.CreateNoWindow = true;

    processInfo.Arguments = args;
    using (Process process = Process.Start(processInfo))
    {
        if (OutputDataReceivedDelegate != null)
        {
            process.OutputDataReceived += OutputDataReceivedDelegate;
            process.BeginOutputReadLine();
        }
        else
        {
            stdOut = process.StandardOutput.ReadToEnd();
        }
        // do not reverse order of synchronous read to end and WaitForExit or deadlock
        // Wait for the process to end.  
        process.WaitForExit();
        returnValue = process.ExitCode;
    }
    return returnValue;
}

答案 1 :(得分:0)

通用流程没有内置机制来提供进度通知。你需要找出一些方法,让你开始了解它的进展。

如果您控制该过程,则可能会将其写入标准输出或标准错误,并使用

outputReader = process.StandardOutput;
errorReader = process.StandardError;

您已定义将该进度读回您的程序。例如,该过程可以写入标准错误

10
31
50
99

并且您的父进程(阅读errorReader)可以将这些单独的行解释为%完成。

一旦您有了完成子流程完成百分比的方法,就可以使用ProgressBar来显示该进度。