using System.Transactions; TransactionOptions options = new TransactionOptions(); options.IsolationLevel = IsolationLevel.ReadCommitted; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options)) { // Perform work under the transaction scope.Complete(); }
using System.Transactions; using (TransactionScope scope = new TransactionScope()) { // Perform work under the transaction throw new Exception("Transaction failed!"); scope.Complete(); // not reached }In this example, we create a transaction using the TransactionScope class and perform some work under the transaction. We then intentionally throw an exception to simulate a failure. Because the transaction was not completed using the Complete method, it is automatically rolled back when the scope is disposed. This ensures that all changes made under the transaction are undone. This example demonstrates how the TransactionScope class can be used to automatically rollback transactions in the event of a failure. Package library: System.Transactions is part of the .NET Framework Class Library and does not require any additional packages to be installed.