...
is the most typical way of creating transactions and a corresponding transaction scope:
ClientTransaction.CreateRootTransaction()
creates a new client (root) transaction (just as the name suggests). It is a static method belonging to the classClientTransaction
.- Form this transaction, and FOR this transaction, a transaction scope is created and prepared for using by
EnterDiscardingScope()
. - this scope is returned to the embracing using
- the using's scope - and with it the root transaction - is delimited by the curly braces '}' and '{'.
A discarding scope is a transaction scope that behaves as explained here: it makes the transaction that belongs to the scope vanish without a trace as soon as execution of the program leaves the scope. (The alternative is FIXME.)
Note how easy it is to answer the following questions for the illustrated listing above:
- Which transaction is referenced by
ClientTransaction.Current
? Answer: the one created for the braces delimiting the transaction scope. - When will the transaction be discarded? Answer: As soon as the code leaves the section delimited by the transaction scope's closing curly bracket '}'.
As explained in the section FIXME above, root transactions are not all there is to it. Sub-transactions are created with the method CreateSubTransaction
. This method is not static, however, it is a member of the given client transaction instance. For spawning a sub-transaction from a given client transaction, just call its CreateSubTransaction()
method. Call EnterDiscardingScope()
like you do for a root transaction.
This works for arbitrarily nested transactions and sub-transactions. Here is a more complicated illustration:
- A.) In this listing, the program creates a new root transaction.
- 1.) This root transaction is valid for the entire outer scope, i.e.
ClientTransaction.Current
in the outer scope references contains a reference to the corresponding root creation for which is has been created. - B.) The sub transaction is spawned off from the root transaction,
2.) i.e. the client transaction referenced in the outer scope'sClientTransaction.Current
. - 3.) Within that inner scope,
ClientTransaction.Current
holds a reference to that sub-transaction for which it has been created. As soon as execution leaves the inner scope, the sub-transaction is forgotten and falls prey to .NET's garbage collector. - 4.) The value of
ClientTransaction.Current
is restored so that it references the outer scope's root transaction again.
Sub-transactions can be spawned and nested to arbitrary depth:
...