Udostępnij za pośrednictwem


Transactions made easy: System.Transactions

Currently in .Net Framework (v1.0 and v1.1) the support for transactions is offered by System.EnterpriseServices and by the System.Data.IDbTransaction, implemented by one of your favorite data provider (see https://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconprocessingtransactions.asp?frame=true for more details). Both models have some disadvantages (the first is forcing the inheritance from ServicedComponent and the later offers support only for "local" transactions in that specific database) and together they don't provide a consistent and complete programming model. If all you need is to use a distributed transaction for protection when interacting with two or more resource managers, the only way to do it today is by taking a cumbersome road of using P/Invoke and COM Interop to access the "old and dusted" MSDTC APIs.

With the first beta preview of the next version of .Net Framework, codename Whidbey (available for download at https://lab.msdn.microsoft.com/vs2005/get/default.aspx ), the pain is over and transactions are here with a bright new and simple programming model, offering an exploding number of possibilities which can make your life simpler, safer and even faster. Please welcome System.Transactions [https://lab.msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/N_System_Transactions.asp?frame=true]

The quick summary of the most important features offered by System.Transactions is: an easy to use programming model, support for transactional code blocks using TransactionScope, the concept of the "ambient" transaction using Transaction.Current, a super fast "lightweight" transaction manager for in appdomain transactions that involve at most a single durable resource manager, automatic promotion from "lightweight" to distributed transactions on a need basis and protection against early commits in an async environment using IDependentTransaction.

Over the next weeks I will go over each of these features, with code samples but for today, let me begin by telling you that all you need to get started is to understand the use of TransactionScope. Here is a small piece of code annotated with my explanations:

 using System;
using System.Transactions;

namespace TxScopeSample
{
    class Program
    {
        static void Main(string[] args)
        {
         // create a new transaction scope and protect it 
         // inside an using statement against unexpected exceptions
         using (TransactionScope ts = new TransactionScope())
         {
            // do the transactional work
            // an "ambient" transaction is placed in the current call context
 
            // USER CODE: open connection to database 1
            // the data provider will detect the ambient transaction and automatically enlist into it
            // USER CODE: execute update in database 1 (for instance a credit operation)
 
            // USER CODE: open connection to database 2
            // the data provider will detect the ambient transaction and automatically enlist into it
            // USER CODE: execute update in database 2 (for instance a debit operation)

            // the following code will be executed only if no exception
            // occured in the above code; since we got here ok, let's vote for commit;
            // in most if not all of the cases, this last line will be the same as below
            ts.Complete(); // was ts.Consistent = true; in beta 2
         }

         // when "using" will be  calling Dispose on the transaction scope at the end
         // of the "using" code block, the "ambient" transaction will be commited only and only if
         // the Complete method was called
      }
   }
}

The only code you need to fill in to get your scenarios running is for the lines marked with "USER CODE". And that is all!

When you get the chance to try System.Transactions, please use this blog entry to send me and my team your comments about it. Tell us what you like and what you don't like about this new programming model, we will certainly listen to your feedback. Thanks!

[UPDATE] In Beta 2, the Consistent flag was replaced with a Complete method. Calling TransactionScope.Complete() is equivalent with the statement "TransactionScope.Consistent = true;".

Comments

  • Anonymous
    July 22, 2004
    Very nice, I've been waiting for it for a long time! Good job!

  • Anonymous
    July 22, 2004
    This is awesome. Is TransactionScope also the way to handle single database (multi-table) transactions?

  • Anonymous
    July 22, 2004
    The comment has been removed

  • Anonymous
    July 22, 2004
    What about [Autocommit] and [TransactionOption] attributes similar to that of the support we have in EnterpriseServices. I remember seeing similar attributes in a presentation from the PDC on Distributed Transactions using the Light weight Transaction Manager.

    We are currently using Remoting interception (derived from ContextBound and applied ContextAttributes) for Distributed Transactions without using EnterpriseServices. Since these classes are not documented and might become internal in future releases of the framework we want to move away from this model and use the System.Transaction classes instead, so we were comparing the options available and wanted to know if similar attributes would be made available in the future...basically we are looking for applying the "using TransctionScope" block through attributes and avoid having to write the plumbing code...

    Thanks !

  • Anonymous
    July 22, 2004
    The comment has been removed

  • Anonymous
    July 23, 2004
    TO: Kyle Tinsley
    Yes, TransactionScope is also good for single-database transactions. In fact, when only one resource manager is used and this resource manager supports promotable transactions, there will be no overhead.

  • Anonymous
    July 23, 2004
    The comment has been removed

  • Anonymous
    July 23, 2004
    To: Krishna 2nd comment

    Currently there are no attributes for transactions as part of System.Transactions namespace. They are provided either by EnterpriseServices or will be by "Indigo" (these are the attributes you've seen at PDC). Or you can write your own attributes. Please, make sure to read my disclaimer.

  • Anonymous
    July 23, 2004
    To: Stuart

    Did you look at ContextUtil.SetAbort()? I believe this is what you are looking for.

    See more info at http://samples.gotdotnet.com/quickstart/aspplus/doc/mtstransactions.aspx

  • Anonymous
    July 25, 2004
    Thanks Florin, I have submitted the code in the link provided..the subject is "System.Transactions Sample Code that throws Exception..See note on Blog" let me know if you need more information..

    how to check the consistency of the transaction?..say a child class has set the transaction scope consistent flag to false..is it possible to check this in the parent class after the call to the child??..

    on the note on Attributes..is there special attribute that we need to inherit from to make the transaction scopes transparent on a method or a class??

    Thanks

  • Anonymous
    January 04, 2005
    Ping Back来自:blog.csdn.net

  • Anonymous
    March 09, 2005
    TrackBack From:http://www.cnblogs.com/coollzh/archive/2005/03/09/115813.html

  • Anonymous
    September 15, 2005
    Hey All,

    Using Beta 2 of VS2005 and I'm attempting to use transaction scope in the business layer with no success. Seems to work ok on XP but when we run in a Windows 2003 environment, it fails with access denied.

    Any ideas?
    Mike

  • Anonymous
    October 03, 2005
    To Mike: It's unusual to get an access denied. I don't know of any case when System.Transactions or DTC return "Access Denied". You should post more details about your scenario.

  • Anonymous
    October 11, 2005
    When two connections opened in the same transactionscope, it triggers a DTC transaction, not a local transaction, even if two connections point to the same database. I use win2003 and sql2005 with .net 2.0 beta 2.

    Is this behaviour as designed?

    Thanks

  • Anonymous
    November 20, 2005
    The comment has been removed

  • Anonymous
    January 11, 2006
    The comment has been removed

  • Anonymous
    January 30, 2006
    To: hbzhang

    The behavior is currently by design. The WebData/ADO team may be able to optimize this in the future if we (me and you) ask them nicely :)

  • Anonymous
    January 30, 2006
    To: Jesús

    Shouldn't you put ts.Complete() after dataset.AcceptChanges? I'm not sure what AcceptChanges does, but if is trying to use the current transaction, that might explain why you are getting the exception.

  • Anonymous
    April 27, 2006
    The comment has been removed

  • Anonymous
    May 01, 2006
    What version of Visual Studio 2005 is needed for the transactional support, or am I just really lost here?I put in using System.Transactions; (Well tried to, doesn't show up in intellisense) but am unable to access anything in the namespace.Was this dropped from the final release of VS2K5 or do I need something better than Standard Edition?

  • Anonymous
    July 19, 2006
    The comment has been removed

  • Anonymous
    September 11, 2006
    The comment has been removed

  • Anonymous
    October 03, 2006
    To: Sundar Paranthaman I recommend looking at the ConnectionScope class from http://blogs.msdn.com/dataaccess/archive/2006/02/14/532026.aspx

  • Anonymous
    February 21, 2007
    To use TransactionScope what needs to be installed and running on Windows 2000 or Windows 2003 server & SQL 2000? Thanks.

  • Anonymous
    February 21, 2007
    To: Dan You need to install .Net Framework 2.0 or higher in order to be able to use System.Transactions.

  • Anonymous
    February 26, 2007
    Hi I am having the same error. In our case the application is on win server 2003 and the sql server on win2k. Do we need to install .NET framework 2 on both servers SQL and Web?

  • Anonymous
    February 28, 2007
    I recommend posting your issues to http://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=388&SiteID=1

  • Anonymous
    July 18, 2008
    Lexapro. Side effects lexapro.

  • Anonymous
    July 27, 2008
    The comment has been removed