【问题标题】:How to run a process in loop and wait for it to complete and then run it again in C# without freezing GUI如何在循环中运行进程并等待它完成,然后在 C# 中再次运行它而不冻结 GUI
【发布时间】:2020-05-07 07:45:09
【问题描述】:

我是 C# 编程的新手,有一段代码我想在循环中多次运行命令行进程。我还想等待命令行过程完成,然后使用不同的参数再次运行它。我所做的是我在一个循环中定义了该过程,并且一切正常。但是,我也想在每次进程结束时更新 GUI 上的进度条,但最终 Process.WaitForExit() 挂起我的 GUI 并且它不会更新进度条。当 for 循环完成时,进度条会更新。请帮帮我,这是我一直在尝试做的。

ProcessStartInfo processInfox = new ProcessStartInfo();
processInfox.CreateNoWindow = false;
processInfox.UseShellExecute = false;
processInfox.FileName = programPath;
processInfox.CreateNoWindow = true;

int startFrames = Convert.ToInt16(txtStartFrame.Text);
int endFrames = Convert.ToInt16(txtEndFrame.Text);

for (int i = startFrames; i <= endFrames; i++)
{
    progressBar1.Value = (i / endFrames) * 100;
    iName = fileFrames + "_" + i + ".jpg";
    oName = outFrames + "\\" + outFileName + "_processed_" + i + ".jpg" ; 
    processInfox.Arguments = "-i \"" + iName + "\"" + progArgs + " -o \"" + oName + "\"";
    using (Process processFire = Process.Start(processInfox))
    {
        processFire.WaitForExit();
    }
}

【问题讨论】:

    标签: c# loops user-interface command-line process


    【解决方案1】:

    将循环放入某个函数(我们称之为foo)并使用await Task.Run(foo) 运行在后台线程中运行进程的代码,同时不阻塞GUI 线程。

    async/await

    Task.Run()

    【讨论】:

      【解决方案2】:
      1. Process 公开了一个名为Exited 的事件,您可以订阅它。不要忘记将EnableRaisingEvents 属性设置为true。订阅应在流程Start之前完成。
      2. 可以冻结进程,因此永远不会触发出口。为了克服这个问题,您可以使用 timeout & kill 模式WaitForExit accepts an int,即超时时间,以毫秒为单位。然后你要检查HasExited属性,如果是false则调用Kill方法。
      3. 根据您的要求,您可以使用后台线程来跨越一个进程。您可以使用new Thread 或使用ThreadPool.QueueUserWorkItem 或使用Task.Run 或...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-24
        • 1970-01-01
        • 2015-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-20
        • 1970-01-01
        相关资源
        最近更新 更多