asmgx
asmgx

Reputation: 8034

c# executing batch file still running after closing my app?

I have this code

    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();
    }

It runs batch file in C#

it is the batch file runs long process which takes few minutes

when I call ExecuteCommand then close the application, the batch file still runs even though app is closed

Is there any way I can control running batch files from within my c# code?

Upvotes: 0

Views: 376

Answers (1)

Louis Go
Louis Go

Reputation: 2588

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

If output is kept filling with info, your thread might be blocked.

Following lines are blocking in your operation

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

That is, process.Close is never called before batch is done.

If abortion is required, you need to close process somewhere else while application is exiting.

I reproduce your problem by

  1. Pasting code snippet to a button clicked event on a small winform application.
  2. Press the button.
  3. UI hung <--- That means code snippet is blocking a (UI) thread.

Upvotes: 1

Related Questions