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

47 Views Asked by At

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
2

There are 2 best solutions below

0
Joe On BEST ANSWER

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.

2
nbk On

No, after End Using will the variable transaction Disposed.

That is one of the things that demand that you use it.

more to using

And yes, the tansaction.complete is necessary before the End Usingas it signalized that the transaction has done its job else it would assume that it is failed, which you don't want.

see manual