Sdílet prostřednictvím


Voting in an Automatic Transaction

.NET Framework classes and ASP.NET pages can vote to commit or abort their current transaction. The absence of an explicit vote in your code casts a commit vote by default. The default commit, however, may decrease the performance of your application by lengthening the time it takes for each transaction to release expensive resources.

Explicit voting also allows your class or page to abort a transaction if it encounters a significant error. Again, you can improve your application's performance by catching a fatal error early in the transaction, ending the transaction, and releasing resources.

Using AutoComplete

The System.EnterpriseServices.AutoCompleteAttribute causes an object participating in a transaction to vote in favor of completing the transaction if the method returns normally. If the method call throws an exception, the transaction is aborted. You can apply this attribute only to classes deriving from the ServicedComponent class.

To use this feature, insert the attribute before the class method. If you add the attribute to an interface method, the common language runtime ignores it. The following code fragment shows the placement of the attribute on a transaction-aware class.

<Transaction(TransactionOption.Supported)> Public Class Account
   Inherits ServicedComponent
   
   <AutoComplete()> Public Sub Debit(amount As Integer)
      ' Do some database work. Any exception thrown here aborts the 
      ' transaction; otherwise, transaction commits.
   End Sub
End Class
[C#][Transaction(TransactionOption.Supported)]
public class Account : ServicedComponent {
    [AutoComplete]
    public void Debit(int amount) {
        // Do some database work. Any exception thrown here aborts the transaction; 
        // otherwise, transaction commits.
    }
}

Using SetAbort and SetComplete

You can use the System.EnterpriseServices.ContextUtil class, which exposes the SetComplete or SetAbort methods, to explicitly commit or abort a transaction. SetComplete indicates that your object votes to commit its work; SetAbort indicates that your object encountered a problem and votes to abort the ongoing transaction. A transaction is neither committed nor aborted until the root object of the transaction deactivates. Further, a single abort vote from any object participating in the transaction causes the entire transaction to fail.

The following code fragment shows the SetAbort and SetComplete methods in use.

'Try to do something crucial to the transaction in progress.
If Not DoSomeWork() Then
   'Something goes wrong.
   ContextUtil.SetAbort()
Else
   'All goes well.
   ContextUtil.SetComplete()
End If
[C#]//Try to do something crucial to the transaction in progress.
if( !DoSomeWork() )
{
  //Something goes wrong.
  ContextUtil.SetAbort();
}
else
{
  //All goes well.
  ContextUtil.SetComplete();
}

See Also

Automatic Transactions