Archive | February, 2009

Add Support for Automatic release of resources in your Classes

11 Feb

This is the part two to my previous topic, where I discussed the .Net Using Statement and showed just a tip on how to implement it.

This time we’ll see how to add support for handling of Unmanaged Resources in your components, simply by Implementing  the IDisposable interface and its Dispose method in your specific component.

How to add support for Unmanaged Resources

I’m going to create a simple class and call it EventLogger. In the class we will use a Filestream and a StreamWritter to write to a physical text file, and we will add support for automatic handling of the unmanaged resources whenever the class is called.

Steps.

  1. Add the IDisposable interface to the class
  2. Add the IDisposable.Dispose method to the class
  3. In the Dispose method, call the FileStream and the StreamWritter’s dispose methods.
  4. When calling the class use the Using Statement.

See the full code below.

Imports System
Imports System.Text
Imports System.IO

Public Class EventLogger
    Implements IDisposable

    Private logFileName As String = "AppLog.txt"
    Private logFile As FileStream = Nothing
    Private sw As StreamWriter = Nothing

    'Initializes a new instance of
    'the class.
    Public Sub New()
        MyBase.New()
        logFile = File.Open(logFileName, FileMode.Append)
        sw = New StreamWriter(logFile)
    End Sub

    ' Adds the specified message to the log.
    Public Sub Add(ByVal message As String)
        sw.WriteLine(message)
    End Sub

    ''' <summary>
    ''' Implements the Dispose() method of the
    ''' IDisposable interface to do application-defined
    ''' tasks like freeing,releasing or resetting of unmanaged
    ''' resources.
    ''' </summary>
    Public Sub Dispose() Implements IDisposable.Dispose
        sw.Dispose()
        logFile.Dispose()
    End Sub

End Class

Simple as that. Now lets see a sample on how to call the class.
In your main procedure implement the using statement to call the class like so.

Module Module1

    Sub Main()

Using mylog As New EventLogger
            mylog.Add(DateTime.Now.ToString & ": What is happening here")
            mylog.Add(DateTime.Now.ToString & ": Yet another message coming in")
        End Using
    End Sub

End Module

Well, this is just one way to kill a bird. You could it in a hundred other ways.

Like for example you could get rid of the Unmanaged resources in the Add method by implementing the Using statement with the StreamWriter,and then in your main method you create a new instance of the class and call the Add method.

But that would be a lot more code. I think this way is safe and leads to less and more readable code.

Hope this was helpful, till next time, yours truly.

Implementing IDisposable.Dispose to automatically release resources from your Derived Classes

4 Feb

The .Net  Using statement defines a scope for an object in which the object will be automatically disposed at the end of the block.  An example will make things easy.

Using cn As New SQLConnection(ConnectionString)
     'implementation code goes here
End Using
'or in this example
'a file stream
Using sw As New StreamWriter("C:\Projects\Sample.txt")
    sw.WriteLine("Just another entry")
End Using

In the example above, when the using block exits, whatever resources that your code usedwithin the block are disposed and can not be accessed outside the using block. The using block guarantees that the system calls the Dispose method which disposed the resources when your code exits the block.

The Dispose method is a member of the IDisposable interface and it is responsible for application-defined tasks associated with freeing, releasing, or resetting unmanaged resources such as files, streams, and handles held by an instance of the class that implements this interface.

The IDisposable Interface

From MSDN, ” The primary use of this (IDisposable) interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams.

Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed. “

How to implement the Using Statement.

To practically show you how, I’m going to create a simple procedure that utilizes the Using statement to write to a text file. The  code within the statement opens a filestream, writes to the file and the closes the file stream.

Imports System.IO
Module Sample
	Sub Main()
		WriteEntry("Application is misbehaving")
	End Sub
Public Sub WriteEntry(ByVal message As String)
	Dim logFile As FileStream = File.Open("C:\Test\Applog.txt", FileMode.Append)
        Using sw As New StreamWriter(logFile)
            sw.WriteLine(message)
        End Using
End Sub

End Module

In the second part of this post I’ll show you how to create classes that can implement the Using block  i.e classes that automatically use the Dispose method to release any resources they might have been using.

Follow

Get every new post delivered to your Inbox.