Harsha
Harsha

Reputation: 1879

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

Upvotes: 8

Views: 4164

Answers (4)

Phil Gan
Phil Gan

Reputation: 2863

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
}

Upvotes: 4

Henrik
Henrik

Reputation: 23324

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;
}

Upvotes: 7

Joe
Joe

Reputation: 11677

The variable proc is local to the foreach loop so once the loop completes, it will automatically be garbage collected.

Upvotes: -3

PedroC88
PedroC88

Reputation: 3829

IF you are looping to find your won process then you could try something like:

Process.GetCurrentProcess();

In any case I would change it to:

    foreach (Process proc in Process.GetProcesses())
    {
        if (proc.ProcessName.ToLower() == ProcessName.ToLower())
        {
            SendMessage(proc.MainWindowHandle, (uint)Message, IntPtr.Zero, IntPtr.Zero);
        }               
    }

That way no variable will refernce the "GetProcesses" and the GC would eventually handle it.

Upvotes: -2

Related Questions