Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I kill a System.Diagnostics.Process with .Kill(), do I also need to call .Close()?

Using C# 4.0, I've created a System.Diagnostics.Process that I expect to take a short amount of time to run. If for some reason the process hasn't exited after some amount of time (e.g, I've called .WaitForExit(timeout) and the return value was false), I need to cleanup. I've decided that it's safe to use .Kill() in this particular situation (there are no data structures I'm worried about corrupting).

Given this setup, do I also need to call the .Close() method of the Process? If so, should I call .Close() before or after .Kill()?

like image 508
Chris Phillips Avatar asked Apr 12 '11 23:04

Chris Phillips


People also ask

What does process kill do?

The Kill method forces a termination of the process, while CloseMainWindow only requests a termination. When a process with a graphical interface is executing, its message loop is in a wait state. The message loop executes every time a Windows message is sent to the process by the operating system.

How do I start a process in C#?

using System. Diagnostics; ... Process. Start("process.exe");


2 Answers

System.Diagnostics.Process implements IDisposable via the Component class, and the protected Dispose(bool) method calls Close(). It is generally considered good practice to dispose of disposable resources when you are done with them, as this will immediately release any resources associated with the class (not having to wait for the GC to run).

So to answer your question:

Yes, please call Close() by calling the Dispose() method directly or via the C# using construct as follows.

using(Process proc = CreateProcess())
{
    StartProcess(proc);
    if (!proc.WaitForExit(timeout))
    {
        proc.Kill();
    }
}
like image 123
Steve Guidi Avatar answered Sep 28 '22 06:09

Steve Guidi


Process.Kill() and Process.Close() both internally call Close() on the private SafeProcessHandle object associated with the process. However, Process.Close() also explicitly resets several other internal members.

Since Process implements IDisposable, you should always call Close() on it when you are done, or wrap it in a using block.

like image 29
Kevin Babcock Avatar answered Sep 28 '22 07:09

Kevin Babcock