Thursday, June 17, 2010

Release resources

Make sure you release all the used resource. Below are some of the examples
  • closing the database connection
  • closing the file handle
  • closing the communication port (RS232, Socket, USB, UDP, etc)
C#- If you are using try catch block, make sure you have
the finally block to release the resources. In some case the resource may
have to be released in catch block. Otherwise the “Using”
(gets compiled to try/finally block) block can be used.

C# example- Below code has StreamWriter and try/catch/finally block.
//make sure the StreamWriter is closed
//make sure thr Monitor is exit
public bool WriteToFile_Local(string strMessage)
{
    bool blnStatus = false;
    StreamWriter objStreamWriter = null;
    if (strMessage != string.Empty && strMessage != null)
    {
        try
        {
            Monitor.Enter(m_objLocker);
            objStreamWriter = new StreamWriter(FilePath, true);
            //logs only the time and not the date
            objStreamWriter.WriteLine(
                DateTime.Now.TimeOfDay + " - " + strMessage
                );
            objStreamWriter.Close();
            Monitor.Exit(m_objLocker);
            blnStatus = true;
        }
        catch (Exception objEx)
        {
            //use messagebox if winforms application
            Console.WriteLine(objEx.StackTrace);
            if (objStreamWriter != null)
            {
               objStreamWriter.Close();
            }
            Monitor.Exit(m_objLocker);
        }
        finally
        {
        }
    }
    return blnStatus;
}

C# example- Below code has StreamWriter and Using block.
//exception has to be handled by the caller
//can not be unit tested using UnitTestingTool class
public void WriteToFile_Local_Using(string strMessage)
{
    StreamWriter objStreamWriter = null;
    if (strMessage != string.Empty && strMessage != null)
    {
        //private member variable
        lock (m_objLocker)
        {
            using (objStreamWriter =
                new StreamWriter(FilePath, true))
            {
                //logs only the time and not the date
                objStreamWriter.WriteLine(
                    DateTime.Now.TimeOfDay + " - " + strMessage
                    );
            }
        }
    }
}

Note: When you are done with the reference variable it need
not be set to null, because once a variable fall out of scope,
it is popped from the stack and the reference is removed.

Rule: Close the database connection.

Rule: Close the communication port.

Rule: Close the file handle.

No comments: