Search code examples
vb.netwcfdispose

service.close() vs. service.abort() - WCF example


In one of the WCF tutorials, I saw the following sample code:

Dim service as ...(a WCF service )

try

   ..

   service.close()

catch ex as Exception()
  ... 

   service.abort()

end try

Is this the correct way to ensure that resources (i.e. connections) are released even under error conditions?


Solution

  • I've had good luck with this model:

    Dim service As New MyService()
    Dim closed As Boolean = False
    Try
        service.Open()
        If Not service.State = ServiceModel.CommunicationState.Opened Then
            ''Handle a not-opened state here
        End If
        service.MyMethod()
        service.Close()
        closed = true
    Catch ex As Exception
        ''Handle errors here
    Finally
        If Not closed Then
            service.Abort()
        End If
    End Try
    service = Nothing