Search code examples
.netvb.netdispose

How to dispose a class properly?


VB.Net 2010. I have a class with timers and a few other things, i.e.

Public Class PlayerClass
    Inherits BodyClass

    '//Variables For TCP/IP Functions
    Public Property ClassInstance As UserClass
    Private Account As String
    Private IP As String
    Private HungerTimer As Timer

    Public Property LeftGrip As WeaponClass
    Public Property RightGrip As WeaponClass

    Public Sub New(....blahblah..)
     ...stuff
     ...
    End Sub
End Class

When I create the class, I initialize everything (New Timer(), New WeaponClass(datahere), etc).

I am having an issue with proper disposing. I found out that setting to the initialized class to nothing doesn't properly dispose of it, since the timers keep running and I am guessing the memory is not freed when the GC comes along.

I been reading alot online but I am confused because alot of people have quite a few answers. Do I call .Dispose() instead? Do I have to stop the timers and dispose them, or just dispose (if that)? Do I dispose the other classes like 'LeftGrip' and 'RightGrip'?

So mainly wondering what the best method would be here. Does public property/private effect disposing at all?

Thanks!


Solution

  • Just follow .NET guidance. If a class has any members that are disposable then it should implement IDisposable itself. Like this:

    Public Class PlayerClass
        Inherits BodyClass
        Implements IDisposable
    
        Public Sub Dispose() Implements IDisposable.Dispose
            HungerTimer.Dispose()
        End Sub
    
        '' etc...
    End Class
    

    So when you're done with a PlayerClass object then you can simply dispose it and the timer stops ticking as well. Do be very careful with a System.Timers.Timer, it is a pretty nasty class. For one, it can still trigger the Elapsed event handler you wrote even after you disposed the timer. For another its Elapsed event runs on a worker thread so you have to be very careful what you do with the player object. In a game you almost always favor a synchronous timer instead. Most typically running off the game clock so stuff like pausing the game becomes very simple to implement.