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.
- Add the IDisposable interface to the class
- Add the IDisposable.Dispose method to the class
- In the Dispose method, call the FileStream and the StreamWritter’s dispose methods.
- 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.