GetProcessesByName and Dispose

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
 
P

Phil Wilson

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.
 
K

Keith

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
 
W

Willy Denoyette [MVP]

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.
 
J

Jon Skeet [C# MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top