Search code examples
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:

    • When you are satisfied that all operations within the scope are completed successfully, you should call this method only once ... It is very good practice to put the call as the last statement in the using block.

    • Failing to call this method aborts the transaction, because the transaction manager interprets this as a system failure, or exceptions thrown within the scope of transaction.