introducing system.transactions nigel watson architect advisor [email protected] developer...
Post on 21-Dec-2015
219 views
TRANSCRIPT
Introducing Introducing System.TransactionsSystem.Transactions
Nigel WatsonNigel WatsonArchitect AdvisorArchitect [email protected]@microsoft.comDeveloper Platform Strategy GroupDeveloper Platform Strategy GroupMicrosoftMicrosoft
DAT214
Why System.Transactions?Why System.Transactions?
Not one, but two Transaction programming Not one, but two Transaction programming models in .NET 1.1models in .NET 1.1
Both models have disadvantagesBoth models have disadvantagesNeither superior to the other in every respectNeither superior to the other in every respect
.NET 2.0 unifies benefits of both models.NET 2.0 unifies benefits of both modelsA single, unified way to create transactional codeA single, unified way to create transactional code
Minimizing hand crafted codeMinimizing hand crafted code
Separate from hosting environment and instance Separate from hosting environment and instance managementmanagement
Who cares about transactions, Who cares about transactions, anyway? anyway?
Transactions in .NET 1.1Transactions in .NET 1.1
string connectionString = "…"; IDbConnection connection = new SqlConnection(connectionString);connection.Open();IDbCommand command = new SqlCommand();command.Connection = connection;IDbTransaction transaction;transaction = connection.BeginTransaction(); //Enlistingcommand.Transaction = transaction;try{ // Interact with database here transaction.Commit();}catch{ // Oops… transaction.Rollback(); //Abort transaction}finally{ connection.Close();}
Explicit Model in .NET 1.1Explicit Model in .NET 1.1
Explicit Model in .NET 1.1 Explicit Model in .NET 1.1
DBDB
ClientClient ObjObj TransactionTransaction
Nice and straight-forwardNice and straight-forward
DBDB
Explicit Model in .NET 1.1 Explicit Model in .NET 1.1
But, breaks with multiple objects…But, breaks with multiple objects…
ClientClient ObjObjTransactionTransaction
ObjObjObjObj
DBDB
Explicit Model in .NET 1.1 Explicit Model in .NET 1.1
… … and breaks even harder with multiple and breaks even harder with multiple objects and multiple resourcesobjects and multiple resources
DBDB
TransactionTransactionObjObj
ObjObjObjObj
DBDB
ClientClient
Distributed Transactions Distributed Transactions
Two or more parties or execution Two or more parties or execution contextscontexts
Impractical to manage in your codeImpractical to manage in your code
Need a dedicated 2pc monitorNeed a dedicated 2pc monitor
Managed on Windows by COM+ DTCManaged on Windows by COM+ DTCSystem serviceSystem service
Creates new transactionsCreates new transactions
Propagates transactions across machinesPropagates transactions across machines
Collects resources votesCollects resources votes
Instructs RMs to rollback or commitInstructs RMs to rollback or commit
Declarative model in .NET 1.1Declarative model in .NET 1.1
To use COM+ DTC from .NET 1.1, you To use COM+ DTC from .NET 1.1, you have two optionshave two options
Code against COM+ directly (via interop)Code against COM+ directly (via interop)
Use System.EnterpriseServicesUse System.EnterpriseServices
using System.EnterpriseServices;
[Transaction]public class MyComponent : ServicedComponent{ [AutoComplete] public void MyMethod() { // Interact with other serviced // components and resource managers }}
Declarative Model in .NET 1.1Declarative Model in .NET 1.1
ProblemsProblems
Derivation from Derivation from ServicedComponentServicedComponentPerformance penalty for non-distributed Performance penalty for non-distributed transactionstransactions
COM+ hosting modelCOM+ hosting model
No easy way for multiple threads to No easy way for multiple threads to participate in same transactionparticipate in same transaction
Transactions in .NET 1.1Transactions in .NET 1.1
So…. You are forced to choose:So…. You are forced to choose:Enterprise Services for distributedEnterprise Services for distributed
ADO.NET (maybe) for localADO.NET (maybe) for local
… … and this gets hard-coded into your appsand this gets hard-coded into your apps
.NET 2.0 Transactions.NET 2.0 Transactions
System.TransactionsSystem.Transactions
Single, unified development modelSingle, unified development modelSupported by ADO.NET 2.0 Supported by ADO.NET 2.0 Lightweight Transaction Manager (LTM)Lightweight Transaction Manager (LTM)
Manages ‘local’ transactionsManages ‘local’ transactionsSingle durable resource, no remotingSingle durable resource, no remoting
Distributed Transaction Manager Distributed Transaction Manager (OleTx)(OleTx)
Manages distributed transactionsManages distributed transactionsMultiple resources, cross app-domainMultiple resources, cross app-domain
Automatic promotion from local to Automatic promotion from local to distributeddistributed
TransactionTransaction
TransactionTransaction represents a local or represents a local or distributed transactiondistributed transaction
No Commit on Transaction objectNo Commit on Transaction object
[Serializable]public class Transaction : IDisposable,ISerializable{ public void Rollback(); //Abort the transaction public void Dispose();
//Other members }
CommittableTransactionCommittableTransaction
CommittableTransactionCommittableTransaction used to used to commit transactioncommit transaction
Allows us to reserve commit for creatorAllows us to reserve commit for creator
Supports Asynchronous commitSupports Asynchronous commit
[Serializable]public sealed class CommittableTransaction : Transaction, IAsyncResult{ public void Commit(); public IAsyncResult BeginCommit(…); public void EndCommit(…);
//Other members}
Ambient TransactionsAmbient Transactions
Ambient TransactionAmbient Transaction
Defines ‘ambient’ transactional contextDefines ‘ambient’ transactional context
Transaction.CurrentTransaction.CurrentMight be nullMight be null
Shared on thread via TLSShared on thread via TLS
Can manage ambient transaction Can manage ambient transaction directlydirectly
But better to use But better to use TransactionScope TransactionScope object object
TransactionScopeTransactionScope
Provides a scoped transaction contextProvides a scoped transaction contextSaves existing ambientSaves existing ambient
Creates Transaction objectCreates Transaction object
Sets Sets Transaction.CurrentTransaction.Current
Complete() memberComplete() memberUsed to vote on transactionUsed to vote on transaction
Sets internal consistency flag (default is false)Sets internal consistency flag (default is false)
Implements IDisposableImplements IDisposableTransaction lifetime defined by scopeTransaction lifetime defined by scope
Fate of transaction rests on consistency flagFate of transaction rests on consistency flag
TransactionScopeTransactionScopetry{ using( TransactionScope scope = new TransactionScope() ) {
// // Transactional code here…
//scope.Complete();
}}catch{ // // Handle exception // throw;}
What happens in Dispose()What happens in Dispose()
Consistency flag checkedConsistency flag checkedIf not set, Transaction is abortedIf not set, Transaction is aborted
If set, Transaction attempts to commitIf set, Transaction attempts to commit
A failed commit throws A failed commit throws TransactionAbortedExceptionTransactionAbortedException
Can alert user or log error Can alert user or log error
Usually better to let exception propagate upUsually better to let exception propagate up
No need to abort in No need to abort in catchcatch block block
Original ambient restoredOriginal ambient restored
Using TransactionScope to Using TransactionScope to make our banking app make our banking app transactional… transactional…
Transaction Flow ManagementTransaction Flow Management
Transaction Flow ManagementTransaction Flow Management
Scopes can nest directly, or indirectlyScopes can nest directly, or indirectlyTop-most is called the root scopeTop-most is called the root scope
TransactionScopeOptionTransactionScopeOption used to used to modify default scoping behaviourmodify default scoping behaviour
RequiredRequired
RequiresNewRequiresNew
SuppressSuppress
More on RequiredMore on Required
When When TransactionScopeTransactionScope joins joins ambient, disposing does not end ambient, disposing does not end transactiontransaction
Ends only when root scope is disposedEnds only when root scope is disposed
Parent and nested scope have distinct Parent and nested scope have distinct consistency bitsconsistency bits
To commit, all scopes in ambient have to be To commit, all scopes in ambient have to be consistentconsistent
Transaction Flow ManagementTransaction Flow Management
Flow decided based on ambient transaction Flow decided based on ambient transaction and and TransactionScopeOptionTransactionScopeOption
TransactionScopeOptionTransactionScopeOption Ambient Ambient TransactionTransaction The scope will take part inThe scope will take part in
RequiredRequired NoNo New Transaction New Transaction (will be the root)(will be the root)
Requires NewRequires New NoNo New Transaction New Transaction (will be the root)(will be the root)
SuppressSuppress NoNo No TransactionNo Transaction
RequiredRequired YesYes Ambient TransactionAmbient Transaction
Requires NewRequires New YesYes New Transaction New Transaction (will be the root)(will be the root)
SuppressSuppress YesYes No TransactionNo Transaction
Nested scopes Nested scopes
Other TransactionScope optionsOther TransactionScope options
TimeoutsTimeoutsDefault is 60 secondsDefault is 60 seconds
After timeout, transaction auto-abortsAfter timeout, transaction auto-aborts
Smallest timeout in nested ambient Smallest timeout in nested ambient transactions usedtransactions used
Use 0 for infinite, but… careful!Use 0 for infinite, but… careful!
Isolation levelIsolation levelDefault is SerializableDefault is Serializable
Departure from this is at own consistency Departure from this is at own consistency risk – make sure you know what you are risk – make sure you know what you are doing…doing…
PromotionPromotion
Transaction Manager PromotionTransaction Manager Promotion
Every Every System.TransactionsSystem.Transactions transaction starts as local transaction transaction starts as local transaction
Single object interacts with single Single object interacts with single durable resourcedurable resource
Only requires local transaction Only requires local transaction
Yields best throughput and performanceYields best throughput and performance
Transaction promoted whenTransaction promoted whenEnlisting another durable RM Enlisting another durable RM
Transaction flows to another object in Transaction flows to another object in another app domainanother app domain
RMs and .NET 2.0RMs and .NET 2.0
Existing RMs cannot participate in a Existing RMs cannot participate in a local transactionlocal transaction
SQL Server 2000SQL Server 2000
OracleOracle
DB2DB2
MSMQ MSMQ
When accessed automatically When accessed automatically promotedpromoted
Even if single resource is involvedEven if single resource is involved
A good reason to switch to SQL2K5 A good reason to switch to SQL2K5
The magic of promotion The magic of promotion
TransactionScope benefitsTransactionScope benefits
Transactional and promotableTransactional and promotable
Independent of object modelIndependent of object model
Auto-enlistmentAuto-enlistment
IntuitiveIntuitive
But, what happens to my But, what happens to my Enterprise Services code?Enterprise Services code?
Declarative Model in .NET 2.0Declarative Model in .NET 2.0
ES code is same as in .NET 1.1ES code is same as in .NET 1.1
Existing components benefit automatically Existing components benefit automatically
Maintains productivity advantagesMaintains productivity advantages
Supports LTM iff single, local resource.Supports LTM iff single, local resource.
using System.EnterpriseServices; [Transaction] //Uses System.Transactions, gets promotion public class MyComponent : ServicedComponent{ [AutoComplete] public void MyMethod() {...}}
Enterprise Services Code in 2.0 Enterprise Services Code in 2.0
ConcurrencyConcurrency
Concurrency ManagementConcurrency Management
Transactions and concurrency? Transactions and concurrency? Uhhh…Uhhh…
One thread aborts the other commitsOne thread aborts the other commits
Ambient transaction stored in TLSAmbient transaction stored in TLSWill not propagate to worker threadsWill not propagate to worker threads
Solution Solution DependentTransactionDependentTransaction
Transaction.DependentClone()Transaction.DependentClone()
Creates a Creates a DependentTransaction DependentTransaction of the existing Transactionof the existing Transaction
Parent keeps tabs on clones, which can Parent keeps tabs on clones, which can be passed to other threadsbe passed to other threads
Must create unique clones for each Must create unique clones for each threadthread
cloneOptioncloneOption parameter to parameter to DependentClone()DependentClone()
RollbackIfNotCompleteRollbackIfNotComplete
BlockCommitUntilCompleteBlockCommitUntilComplete
Concurrent transactionsConcurrent transactions
Roll your own transactional Roll your own transactional typestypes
Create your own transactional typesCreate your own transactional types
Any object that implements Any object that implements IEnlistmentNotificationIEnlistmentNotification can enlist in can enlist in transactionstransactionsCall Call Transaction.EnlistVolatile()Transaction.EnlistVolatile() or or Transacation.EnlistDurable()Transacation.EnlistDurable() to be to be notified of important transaction lifecycle notified of important transaction lifecycle eventsevents
Prepare()Prepare()Commit()Commit()Rollback()Rollback()
Consider extending implementation to Consider extending implementation to include include ISinglePhaseNotificationISinglePhaseNotification for for single-phase commit supportsingle-phase commit support
Transactional int class Transactional int class
SummarySummary
Existing .NET 1.1 transactional Existing .NET 1.1 transactional approaches may paint you into a cornerapproaches may paint you into a corner
.NET 2.0 introduces new unified .NET 2.0 introduces new unified transactional model that unifies explicit transactional model that unifies explicit and declarative approachesand declarative approaches
Writing reliable code much easier with Writing reliable code much easier with transactionstransactions
Can make pretty much anything Can make pretty much anything transactional in .NET 2.0transactional in .NET 2.0
We invite you to participate in ourWe invite you to participate in our online evaluationonline evaluation on CommNet,on CommNet,
accessible Friday onlyaccessible Friday only
If you choose to complete the evaluation online, If you choose to complete the evaluation online, there isthere is no need to complete the paper evaluationno need to complete the paper evaluation
Get a 48% Discount on MSDN Get a 48% Discount on MSDN Universal Now!Universal Now! For a limited time purchase a 12 month For a limited time purchase a 12 month
MSDN Universal Subscription for MSDN Universal Subscription for $3565+GST (RRP).$3565+GST (RRP).
You will receive updates as they are You will receive updates as they are released for SQL Server, BizTalk Server, released for SQL Server, BizTalk Server, Visual Studio, Exchange Server and Visual Studio, Exchange Server and Windows Server. Windows Server.
You will also receive early access to beta You will also receive early access to beta products such as Windows Vista and products such as Windows Vista and Office 12.Office 12.
Get in now so that when Visual Studio Get in now so that when Visual Studio Team System ships you will be upgraded Team System ships you will be upgraded at no cost to one of the new top tier at no cost to one of the new top tier subscriptions:subscriptions:
Visual Studio 2005 Team Edition for Visual Studio 2005 Team Edition for Software DevelopersSoftware DevelopersVisual Studio 2005 Team Edition for Visual Studio 2005 Team Edition for Software ArchitectsSoftware ArchitectsVisual Studio 2005 Team Edition for Visual Studio 2005 Team Edition for Software TestersSoftware Testers
For more details and to find your local For more details and to find your local reseller visit: reseller visit: www.microsoft.co.nz/buyMSDNwww.microsoft.co.nz/buyMSDN
© 2005 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.