static void AmbientTransactions() { using (var scope = new TransactionScope()) { Transaction.Current.TransactionCompleted += (sender, e) => DisplayTransactionInformation("TX completed", e.Transaction.TransactionInformation); DisplayTransactionInformation("Ambient TX created", Transaction.Current.TransactionInformation); var b = new Book { Title = "Cats in The House", Publisher = "Pet Show", Isbn = RandomIsbn(), ReleaseDate = new DateTime(2019, 11, 24) }; var data = new BookData(); data.AddBook(b); if (!AbortTx()) { scope.Complete(); } else { Console.WriteLine("transaction abort by the user"); } } // scope.Dispose(); }
static void NestedScopes() { using (var scope = new TransactionScope()) { Transaction.Current.TransactionCompleted += (sender, e) => DisplayTransactionInformation("TX completed", e.Transaction.TransactionInformation); DisplayTransactionInformation("Ambient TX created", Transaction.Current.TransactionInformation); var b = new Book { Title = "Dogs in The House", Publisher = "Pet Show", Isbn = RandomIsbn(), ReleaseDate = new DateTime(2020, 11, 24) }; var data = new BookData(); data.AddBook(b); using (var scope2 = new TransactionScope(TransactionScopeOption.RequiresNew)) { Transaction.Current.TransactionCompleted += (sender, e) => DisplayTransactionInformation("Inner TX completed", e.Transaction.TransactionInformation); DisplayTransactionInformation("Inner TX scope", Transaction.Current.TransactionInformation); var b1 = new Book { Title = "Dogs and Cats in The House", Publisher = "Pet Show", Isbn = RandomIsbn(), ReleaseDate = new DateTime(2021, 11, 24) }; var data1 = new BookData(); data1.AddBook(b1); if (!AbortTx()) { scope2.Complete(); } else { Console.WriteLine("transaction abort by the user"); } } if (!AbortTx()) { scope.Complete(); } else { Console.WriteLine("transaction abort by the user"); } // scope.Complete(); } }