vb.nettransactionsusing

Do I need both Dispose() and Complete() methods in a transaction to achieve a roll back in case of failure?


In the following code do I need both of the these methods in order to achieve a rollback in case of a failure; Or the Using-End Using covers that case already?

Public Function ProcessMultipleMessages() As String
    Dim messages = GetObjectFromXml(Of ItemList)()

    Using transaction = CreateTransactionScope()
        For Each message In messages.SpecialItems
            Dim errorMsg = ProcessSingleMessage(message)
            If Not String.IsNullOrEmpty(errorMsg) Then
                transaction.Dispose()  '<--- Here
                Return result
            End If
        Next
        transaction.Complete() '<--- Here
    End Using

    Return String.Empty
End Function

Solution

  • If you exit the Using transaction ... End Using block without calling transaction.Complete(), then the transaction will be rolled back by the Dispose method.

    Therefore, in your code, the transaction.Dispose statement is not needed.

    The documentation for TransactionScope.Complete says: