views:

73

answers:

1

In theory since SqlCommand implements IDisposable a SqlCommand object should always be disposed. I personally wrap a using statement around them. However I see lots of code that never disposes of SqlCommand objects without any apparent problems.

I understand that finalizers will ultimately be called by garbage collection but since that can take quite a while in most cases (and never in others) why isn't the code crashing due to running out of some resource?

In our own code base we have code that runs 24x7 without disposing of commands. I'd like to clean it up but it's hard to justify when it's not causing any problems.

+2  A: 

Looks to me like it calls the base class (Component) Dispose method, and jump-starts garbage collection...

Public Sub Dispose(ByVal disposing As Boolean)
    If disposing Then 'Same as Component.Dispose()            
        SyncLock Me
            If Me.site IsNot Nothing AndAlso Me.site.Container IsNot Nothing Then
                Me.site.Container.Remove(Me)
            End If
            If Me.events IsNot Nothing Then
                Dim handler As EventHandler = DirectCast(Me.events.Item(Component.EventDisposed), EventHandler)
                If handler IsNot Nothing Then
                    handler.Invoke(Me, EventArgs.Empty)
                End If
            End If
        End SyncLock
    End If

    GC.SuppressFinalize(Me)
End Sub

I got this by using Reflector.

Josh Stodola
Ok then what does Component dispose? I guess I should figure out how to use Reflector. :-)
Kevin Gale
Maybe I misunderstood. Is that the code for Component above?
Kevin Gale
That is the Dispose function for SqlCommand. I don't think you need to change all of your code.
Josh Stodola
Ok thanks, So I'll continue placing using statements around the SqlCommand but from a practical standpoint it's not doing anything critical and there isn't any justification to spend time cleaning up code.
Kevin Gale
Yes, `Using` statements are perfect because they automatically dispose at the appropriate time. However, not using a `using` (haha) is not detrimental. I <3 GC!
Josh Stodola