Please explain the process termination mechanism in the c # winforms application. In my application, there is a loop that runs cmd to execute a command. Depending on the launch parameters, the command may work at different times, therefore it is necessary to give time to wait for completion.

So far I have done this:

Process vote = new Process(); vote.StartInfo = new ProcessStartInfo(@"cmd"); vote.StartInfo.RedirectStandardOutput = true; vote.StartInfo.RedirectStandardInput = true; vote.StartInfo.UseShellExecute = false; vote.StartInfo.CreateNoWindow = true; vote.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; vote.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler); vote.Start(); vote.StandardInput.WriteLine(vote_string); vote.BeginOutputReadLine(); vote.WaitForExit(7000); vote.Close(); 

At the same time, I notice in the task manager that sometimes there are too many running cmd, which clogs the RAM and leads to a performance drop.

I began to study msdn on the topic of stopping processes and still did not understand how to organize the release of resources in my case.

In essence, the questions are as follows:

  1. Is cmd shutting down on successful completion? seemingly not

  2. how to use waitforexit correctly? after all, it does not imply the release of resources, but only indicates whether the process is completed or not. Apparently, it is necessary to write an if-block, which, in the case of a negative answer from waitforexit, will forcibly close the process, is that so?

  3. What method to use to complete the process? about close () it says that it frees up resources. Does the process terminate or do you still need to use kill ()?

    1 answer 1

    1. Not.
    2. WaitForExit does nothing with the process. She only waits for the allotted time until the process completes work.
    3. About ways to close the process: https://stackoverflow.com/questions/13952635/what-are-the-differences-between-kill-process-and-close-process

    Most likely you give the command line command to run other applications. And the problem is that those applications are executed, but the command lines remain. If this is the case, then instead of creating command-line processes, you can start processes with the necessary commands.

     var proc = Process.Start("C:\myprog.exe /param"); proc.WaitForExit(7000); 

    In this case, it will wait for the command to complete, not the command line.

    Or, if you need to run command lines, in order to understand whether a command has completed or not, you need to analyze the command line output:

     var result = vote.StandardOutput.ReadToEnd(); 

    And on the content of the result to conclude the completion of the command. Also in this case, it would be good to reuse the existing command line (or several) by sending commands to it in turn, rather than creating a new process each time.

    • Thanks, I experiment. I run cUrl, so your proposal is very appropriate. - iamx4nd3r