Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introducing System.Transactions Nigel Watson Architect Advisor Developer Platform Strategy Group Microsoft DAT214.

Similar presentations


Presentation on theme: "Introducing System.Transactions Nigel Watson Architect Advisor Developer Platform Strategy Group Microsoft DAT214."— Presentation transcript:

1 Introducing System.Transactions Nigel Watson Architect Advisor nigelwat@microsoft.com Developer Platform Strategy Group Microsoft DAT214

2 Why System.Transactions? Not one, but two Transaction programming models in.NET 1.1 Both models have disadvantages Neither superior to the other in every respect.NET 2.0 unifies benefits of both models A single, unified way to create transactional code Minimizing hand crafted code Separate from hosting environment and instance management

3 Who cares about transactions, anyway?

4 Transactions in.NET 1.1

5 string connectionString = "…"; IDbConnection connection = new SqlConnection(connectionString); connection.Open(); IDbCommand command = new SqlCommand(); command.Connection = connection; IDbTransaction transaction; transaction = connection.BeginTransaction(); //Enlisting command.Transaction = transaction; try { // Interact with database here transaction.Commit(); } catch { // Oops… transaction.Rollback(); //Abort transaction } finally { connection.Close(); } Explicit Model in.NET 1.1

6 DB Client Obj Transaction Nice and straight-forward

7 DB Explicit Model in.NET 1.1 But, breaks with multiple objects… Client Obj Transaction Obj Obj

8 DB Explicit Model in.NET 1.1 … and breaks even harder with multiple objects and multiple resources DB Transaction Obj Obj Obj DB Client

9 Distributed Transactions Two or more parties or execution contexts Impractical to manage in your code Need a dedicated 2pc monitor Managed on Windows by COM+ DTC System service Creates new transactions Propagates transactions across machines Collects resources votes Instructs RMs to rollback or commit

10 Declarative model in.NET 1.1 To use COM+ DTC from.NET 1.1, you have two options Code against COM+ directly (via interop) Use System.EnterpriseServices using System.EnterpriseServices; [Transaction] public class MyComponent : ServicedComponent { [AutoComplete] public void MyMethod() { // Interact with other serviced // components and resource managers }

11 Declarative Model in.NET 1.1 Problems Derivation from ServicedComponent Performance penalty for non-distributed transactions COM+ hosting model No easy way for multiple threads to participate in same transaction

12 Transactions in.NET 1.1 So…. You are forced to choose: Enterprise Services for distributed ADO.NET (maybe) for local … and this gets hard-coded into your apps

13 .NET 2.0 Transactions

14 System.Transactions Single, unified development model Supported by ADO.NET 2.0 Lightweight Transaction Manager (LTM) Manages ‘local’ transactions Single durable resource, no remoting Distributed Transaction Manager (OleTx) Manages distributed transactions Multiple resources, cross app-domain Automatic promotion from local to distributed

15 Transaction Transaction represents a local or distributed transaction No Commit on Transaction object [Serializable] public class Transaction : IDisposable,ISerializable { public void Rollback(); //Abort the transaction public void Dispose(); //Other members }

16 CommittableTransaction CommittableTransaction used to commit transaction Allows us to reserve commit for creator Supports Asynchronous commit [Serializable] public sealed class CommittableTransaction : Transaction, IAsyncResult { public void Commit(); public IAsyncResult BeginCommit(…); public void EndCommit(…); //Other members }

17 Ambient Transactions

18 Ambient Transaction Defines ‘ambient’ transactional context Transaction.Current Might be null Shared on thread via TLS Can manage ambient transaction directly But better to use TransactionScope object

19 TransactionScope Provides a scoped transaction context Saves existing ambient Creates Transaction object Sets Transaction.Current Complete() member Used to vote on transaction Sets internal consistency flag (default is false) Implements IDisposable Implements IDisposable Transaction lifetime defined by scope Fate of transaction rests on consistency flag

20 TransactionScope try { using( TransactionScope scope = new TransactionScope() ) { // // Transactional code here… // scope.Complete(); } catch { // // Handle exception // throw; }

21 What happens in Dispose() Consistency flag checked If not set, Transaction is aborted If set, Transaction attempts to commit A failed commit throws TransactionAbortedException Can alert user or log error Usually better to let exception propagate up No need to abort in catch block Original ambient restored

22 Using TransactionScope to make our banking app transactional…

23 Transaction Flow Management

24 Scopes can nest directly, or indirectly Top-most is called the root scope TransactionScopeOption used to modify default scoping behaviour RequiredRequiresNewSuppress

25 More on Required When TransactionScope joins ambient, disposing does not end transaction Ends only when root scope is disposed Parent and nested scope have distinct consistency bits To commit, all scopes in ambient have to be consistent

26 Transaction Flow Management Flow decided based on ambient transaction and TransactionScopeOption TransactionScopeOption Ambient Transaction The scope will take part in RequiredNo New Transaction (will be the root) Requires New No New Transaction (will be the root) SuppressNo No Transaction RequiredYes Ambient Transaction Requires New Yes New Transaction (will be the root) SuppressYes No Transaction

27 Nested scopes

28 No Ambient Transaction Code block {Required} 1 {Required} 2 {RequiresNew} 3 {Suppress} 4 Transaction A Transaction B Transaction Flow Management

29 Other TransactionScope options Timeouts Default is 60 seconds After timeout, transaction auto-aborts Smallest timeout in nested ambient transactions used Use 0 for infinite, but… careful! Isolation level Default is Serializable Departure from this is at own consistency risk – make sure you know what you are doing…

30 Promotion

31 Transaction Manager Promotion Every System.Transactions transaction starts as local transaction Single object interacts with single durable resource Only requires local transaction Yields best throughput and performance Transaction promoted when Enlisting another durable RM Transaction flows to another object in another app domain

32 RMs and.NET 2.0 Existing RMs cannot participate in a local transaction SQL Server 2000 OracleDB2MSMQ When accessed automatically promoted Even if single resource is involved A good reason to switch to SQL2K5 A good reason to switch to SQL2K5

33 The magic of promotion

34 TransactionScope benefits Transactional and promotable Independent of object model Auto-enlistmentIntuitive

35 But, what happens to my Enterprise Services code?

36 Declarative Model in.NET 2.0 ES code is same as in.NET 1.1 Existing components benefit automatically Maintains productivity advantages Supports LTM iff single, local resource. using System.EnterpriseServices; [Transaction] //Uses System.Transactions, gets promotion public class MyComponent : ServicedComponent { [AutoComplete] public void MyMethod() {...} }

37 Enterprise Services Code in 2.0

38 Concurrency

39 Concurrency Management Transactions and concurrency? Uhhh… One thread aborts the other commits Ambient transaction stored in TLS Will not propagate to worker threads SolutionDependentTransaction

40 Transaction.DependentClone() Creates a DependentTransaction of the existing Transaction Parent keeps tabs on clones, which can be passed to other threads Must create unique clones for each thread cloneOption parameter to DependentClone() RollbackIfNotCompleteBlockCommitUntilComplete

41 Concurrency Management If worker thread aborts but client tries to commit TransactionAbortedException On clone only call Complete() once InvalidOperationException

42 Concurrent transactions

43 Roll your own transactional types

44 Create your own transactional types Any object that implements IEnlistmentNotification can enlist in transactions Call Transaction.EnlistVolatile() or Transacation.EnlistDurable() to be notified of important transaction lifecycle events Prepare()Commit()Rollback() Consider extending implementation to include ISinglePhaseNotification for single-phase commit support

45 Transactional int class

46 Summary Existing.NET 1.1 transactional approaches may paint you into a corner.NET 2.0 introduces new unified transactional model that unifies explicit and declarative approaches Writing reliable code much easier with transactions Can make pretty much anything transactional in.NET 2.0

47 We invite you to participate in our online evaluation on CommNet, accessible Friday only If you choose to complete the evaluation online, there is no need to complete the paper evaluation Your Feedback is Important!

48

49 Get a 48% Discount on MSDN Universal Now! For a limited time purchase a 12 month MSDN Universal Subscription for $3565+GST (RRP). You will receive updates as they are released for SQL Server, BizTalk Server, Visual Studio, Exchange Server and Windows Server. You will also receive early access to beta products such as Windows Vista and Office 12. Get in now so that when Visual Studio Team System ships you will be upgraded at no cost to one of the new top tier subscriptions: Visual Studio 2005 Team Edition for Software Developers Visual Studio 2005 Team Edition for Software Architects Visual Studio 2005 Team Edition for Software Testers For more details and to find your local reseller visit: www.microsoft.co.nz/buyMSDN www.microsoft.co.nz/buyMSDN

50 © 2005 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

51


Download ppt "Introducing System.Transactions Nigel Watson Architect Advisor Developer Platform Strategy Group Microsoft DAT214."

Similar presentations


Ads by Google