Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to worry about Process in foreach loop

Here is the piece of code, which run through all the process and when It finds the right process, code sends the message. My question is what happened to the 'proc', how to dispose that process.

//get all other (possible) running instances
        Process[] processes = Process.GetProcesses();            
        foreach (Process proc in processes)
        {
            if (proc.ProcessName.ToLower() == ProcessName.ToLower())
            {
                SendMessage(proc.MainWindowHandle, (uint)Message, IntPtr.Zero, IntPtr.Zero);
            }               
        }

Thanks in advance, Harsha

like image 651
Harsha Avatar asked Feb 23 '11 12:02

Harsha


2 Answers

To make sure all resoucers are freed as early as possible, call Dispose on the process, when you no longer need it.

//get all other (possible) running instances
Process[] processes = Process.GetProcesses();
try
{
    foreach (Process proc in processes)
    {
    // use proc
    }
}
finally
{
    foreach (Process proc in processes)
        proc.Dispose();
    processes = null;
}
like image 128
Henrik Avatar answered Oct 16 '22 22:10

Henrik


In general terms you don't need to worry about disposing or deallocating objects, unless the object implements the IDisposable interface. If it does you should either call the Dispose() method on it manually when you're finished, or wrap with a using statement to have it called automatically:

using (var disposableObject = new DisposableType())
{
    // do work with disposableObject
}
like image 39
Phil Gan Avatar answered Oct 17 '22 00:10

Phil Gan