【问题标题】:c# executing batch file still running after closing my app?c#关闭我的应用程序后执行批处理文件仍在运行?
【发布时间】:2020-05-26 01:00:39
【问题描述】:

我有这个代码

    public static void ExecuteCommand(string command, string workingFolder, int TimeoutMin)
    {
        int ExitCode;
        ProcessStartInfo ProcessInfo;
        Process process;

        ProcessInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
        ProcessInfo.CreateNoWindow = true;
        ProcessInfo.UseShellExecute = false;
        ProcessInfo.WorkingDirectory = workingFolder;
        // *** Redirect the output ***
        ProcessInfo.RedirectStandardError = true;
        ProcessInfo.RedirectStandardOutput = true;

        process = Process.Start(ProcessInfo);
        process.WaitForExit(TimeoutMin * 1000 * 60);

        // *** Read the streams ***
        string output = process.StandardOutput.ReadToEnd();
        string error = process.StandardError.ReadToEnd();

        ExitCode = process.ExitCode;

        MessageBox.Show("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
        MessageBox.Show("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
        MessageBox.Show("ExitCode: " + ExitCode.ToString(), "ExecuteCommand");
        process.Close();
    }

它在 C# 中运行批处理文件

这是批处理文件运行的漫长过程,需要几分钟

当我调用 ExecuteCommand 然后关闭应用程序时,即使应用程序关闭,批处理文件仍会运行

有什么方法可以在我的 c# 代码中控制运行批处理文件吗?

【问题讨论】:

    标签: c#


    【解决方案1】:

    根据C# process hanging due to StandardOutput.ReadToEnd() and StandardError.ReadToEnd()Hanging process when run with .NET Process.Start -- what's wrong?

    如果输出不断填充信息,您的线程可能会被阻塞。

    以下行在您的操作中阻塞

        process.WaitForExit(TimeoutMin * 1000 * 60);
        string output = process.StandardOutput.ReadToEnd();
        string error = process.StandardError.ReadToEnd();
    

    也就是说,在批处理完成之前永远不会调用process.Close

    如果需要中止,您需要在应用程序退出时在其他地方关闭process

    我通过

    重现您的问题
    1. 将代码 sn-p 粘贴到小型 Winform 应用程序上的按钮单击事件。
    2. 按下按钮。
    3. UI 挂起

    【讨论】:

      猜你喜欢
      • 2021-08-16
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      • 2013-02-03
      • 2023-01-12
      • 1970-01-01
      • 2011-04-02
      • 2021-05-17
      相关资源
      最近更新 更多