Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What gets disposed when SqlCommand.Dispose is called?

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.

like image 728
Kevin Gale Avatar asked Jun 02 '26 01:06

Kevin Gale


1 Answers

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.

like image 141
Josh Stodola Avatar answered Jun 03 '26 14:06

Josh Stodola