简体   繁体   中英

How to keep batch file running while C# program quit?

I have a wrote a C# code that would read several .xml files(Containing executable, path, parameters. The .xml files contains a series of executable that need to be run) and several batch file will be created associate with the .xml file.

After each batch file is created, the program would execute each batch file in the C# code (using cmd of course). The problem is some of the batch file would run for days and it is a waste of memory/instants to keep the C# program running. Is it possible to keep the .bat file running and close the C# code? Assuming that we do not need any error reporting from the C# code.

Below is the code for executing a batch file.

    //Execute BatchFile
    public static void ExecuteCommand(string command, string dummyPath)
    {
        int exitCode;
        ProcessStartInfo processInfo;
        Process process;

        processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
        processInfo.WorkingDirectory = dummyPath;
        processInfo.CreateNoWindow = true;
        processInfo.UseShellExecute = false;
        processInfo.RedirectStandardError = true;
        processInfo.RedirectStandardOutput = true;

        process = Process.Start(processInfo);
        process.WaitForExit();

        string output = process.StandardOutput.ReadToEnd();
        string error = process.StandardError.ReadToEnd();

        exitCode = process.ExitCode;

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

If I understand you correctly, I think it is possible if you don't need any feedback from the .bat file. I have tested this line of code on my own machine and it worked fine.

    static void Main(string[] args)
    {
        System.Diagnostics.Process.Start(@"d:\simple.bat");
    }

and for testing purpose I simply put PING www.google.com inside my .bat file.

The cmd batch process is belong to your program process, main process stop and sub processes will be killed.

I think you can try to create windows task schedule in your program, run batch in the taski, program stop and task schedule will still runnning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM