Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between Process.Close() and Process.Dispose()?

Tags:

c#

process

I start a Process then I want to make sure it will be closed properly. I have used Process.Close() to close it but sometime it was still locking the resources. I can see we have Process.Dispose() method. I just want to know what are the actual differences between them and should I call them both to make sure that process will be closed?

p.Dispose();
p.Close();
like image 536
Minh Nguyen Avatar asked Nov 19 '15 11:11

Minh Nguyen


3 Answers

From documentation of Process.Close();

The Dispose method calls Close. Placing the Process object in a using block disposes of resources without the need to call Close.

That means, there is no difference. Internally, all Close methods in .NET calls Dispose method as far as I know.

If you look at reference source;

public void Close()
{
      ...        
      m_processHandle.Close();
      ...
}

and this method calls;

public void Close() {
    Dispose(true);
}

You should always use using statement for a Process object. It allows early cleanup of resources so you don't need to wait until they garbage collected.

like image 163
Soner Gönül Avatar answered Nov 01 '22 07:11

Soner Gönül


Difference between Close() and Dispose() Method

Close() Vs Dispose() Method

The basic difference between Close() and Dispose() is, when a Close() method is called, any managed resource can be temporarily closed and can be opened once again. It means that with the same object the resource can be reopened or used. Whereas Dispose() method permanently removes any ((un)managed) resource from memory for cleanup and the resource no longer exists for any further processing.

Example showing difference between Close() and Dispose() Methods:

using System;
using System.Data;
using System.Data.SqlClient;

public class Test
{
    private string connString = "Data Source=COMP3;Initial Catalog=Northwind;User Id=sa;Password=pass";
    private SqlConnection connection;

    public Test()
    {
        connection = new SqlConnection(connString);
    }

    private static void Main()
    {
        Test t = new Test();
        t.ConnectionStatus();
        Console.ReadLine();
    }

    public void ConnectionStatus()
    {
        try
        {
            if(connection.State == ConnectionState.Closed)
            {
                connection.Open();
                Console.WriteLine("Connection opened..");
            }

            if(connection.State == ConnectionState.Open)
            {
                connection.Close();
                Console.WriteLine("Connection closed..");
            }
            // connection.Dispose();

            if(connection.State == ConnectionState.Closed)
            {
                connection.Open();
                Console.WriteLine("Connection again opened..");
            }
        }
        catch(SqlException ex)
        {
            Console.WriteLine(ex.Message+"\n"+ex.StackTrace);
        }
        catch(Exception ey)
        {
            Console.WriteLine(ey.Message+"\n"+ey.StackTrace);
        }
        finally
        {
            Console.WriteLine("Connection closed and disposed..");
            connection.Dispose();
        }
    }
}

In the above example if you uncomment the connection.Dispose() method and execute, you will get an exception such as

The ConnectionString property has not been initialized.

This is the difference between Close() and Dispose().

like image 3
Engr. Khuram Shahzad Avatar answered Nov 01 '22 06:11

Engr. Khuram Shahzad


Dispose normally free's the UnManaged resources that are held inside the class. It has no effect on the process itself.

so far to dispose. As taken from the MSDN the Close mehtod does:

Frees all the resources that are associated with this component. ref: MSDN Process.Close()

So from the outside there is no difference, but lets take a look in the glorious .net SourceCode: Process

   /// <devdoc>
    ///    <para>
    ///       Frees any resources associated with this component.
    ///    </para>
    /// </devdoc>
    public void Close() {
        if (Associated) {
            if (haveProcessHandle) {
                StopWatchingForExit();
                Debug.WriteLineIf(processTracing.TraceVerbose, "Process - CloseHandle(process) in Close()");
                m_processHandle.Close();
                m_processHandle = null;
                haveProcessHandle = false;
            }
            haveProcessId = false;
            isRemoteMachine = false;
            machineName = ".";
            raisedOnExited = false;

            //Don't call close on the Readers and writers
            //since they might be referenced by somebody else while the 
            //process is still alive but this method called.
            standardOutput = null;
            standardInput = null;
            standardError = null;

            output = null;
            error = null;


            Refresh();
        }
    }

while dispose does this

    /// <internalonly/>
    /// <devdoc>
    ///    <para>
    ///       Free any resources associated with this component.
    ///    </para>
    /// </devdoc>
    protected override void Dispose(bool disposing) {
        if( !disposed) {
            if (disposing) {
                //Dispose managed and unmanaged resources
                Close();
            }
            this.disposed = true;
            base.Dispose(disposing);                
        }            
    }

So as you can see, even internally there is no difference. Dispose just wraps the close mehtod.

like image 2
Venson Avatar answered Nov 01 '22 07:11

Venson