GetProcessesByName and Dispose

  • Thread starter Thread starter Keith
  • Start date Start date
K

Keith

Hi,

I am calling GetProcessesByName, and I'd like to know if I need to loop
through the array and call Dispose on each Process object when I'm
done. It seems that Dispose is only required in the case of unmanaged
resources, but I'm not sure whether this qualifies as unmanaged.

thanks,
Keith
 
The best general rule is that if a class has a Dispose (or Close) method,
call it when you're done with using the object to release the resources used
by the object. Dispose isn't required for unmanaged resources, it's just a
way you can tell the object to release them early compared to having them
released by its Finalizer. The Process class wraps an unmanaged handle,
Dispose will close it if necessary.
 
Okay, thanks. Resource cleanup is one thing that never seems to make
its way into MSDN samples. They also don't document what methods of a
given class use unmanaged resources.

Keith
 
Keith said:
Okay, thanks. Resource cleanup is one thing that never seems to make
its way into MSDN samples. They also don't document what methods of a
given class use unmanaged resources.

Keith

Be carefull, when calling Dispose (or Close) on a Process (closing the
process handle) you effectively kill that process (subject to privilege
constrainst). That means, that you should not call Dispose when enumerating
running processesn unless you want to kill them all ;-)

Willy.
 
Willy Denoyette said:
Be carefull, when calling Dispose (or Close) on a Process (closing the
process handle) you effectively kill that process (subject to privilege
constrainst). That means, that you should not call Dispose when enumerating
running processesn unless you want to kill them all ;-)

I haven't seen that behaviour at all. Could you demonstrate it at all?
Here's something which seems to contradict it:

using System;
using System.Diagnostics;

public class Test
{
static void Main()
{
Process proc = Process.Start("notepad.exe");
Console.WriteLine ("Started");
Console.ReadLine();
proc.Dispose();
//proc.Kill();

Console.WriteLine("Disposed");
Console.ReadLine();
}
}

As written above, Notepad stays up.
Uncommenting the "Kill" line and commenting out the "Dispose" line, the
process terminates as expected (so there's no privilege problem there).

Dispose will close the process handle, but that doesn't kill the
process as far as I'm aware.
 
Back
Top