Use of TransactionScope

Source: Internet
Author: User

This article is guided by: in the actual development work, execute an event, and then call another interface to insert data, if the processing logic is abnormal, then the previously inserted data will become garbage data, we want to be able to define the whole method as a transaction, TransactionScope class provides a simple method by which you can mark a block of code as participating in a transaction without interacting with the transaction itself. The TransactionScope object creates a transaction and sets the transaction to the current property of the transaction class.

First, the advantages of TransactionScope


1, the use of more convenient. TransactionScope can implement implicit transactions, allowing you to write data access layer code without taking into account the transaction, while at the business level of the control transaction.

2, you can implement distributed transactions, such as cross-Library or MSMQ.

Second, TransactionScope shortcomings

1, the price is not high. For example, you just control a library's transaction in Scope. "TransactionScope" is a bit wasteful.
2, in general, as long as you use "TransactionScope", you have to configure MSDTC, to be equipped with a firewall, to open 139 ports. This port cannot be changed

Third, if you have to use distributed transactions, it also has to ponder

1. Does this operation have to be in the business? Is it worth rolling back the entire transaction if it has not been completed or failed? Are there no elegant compensation measures or fault-tolerant measures?

2. What are the points involved in distributed transactions that must be so much? Must be in real-time operation of this large string? Unable to refine some points by notifying class operations?

3. After initiating a distributed transaction, did you do a transaction-independent operation, even though these operations are not related to the transaction? (for example, reading data, computing, returning messages to other modules, and so on, etc.), knowing that the transaction should end as soon as possible.

4. You didn't put some read operations in the business, did you? This is a very easy mistake, and you enlist a select operation in the transaction.

5. Your operation, some of the steps can be completed after the completion of the operation. This type of operation has obvious characteristics of the notification class. The notification class action is to say, I give you a notice, and I promise to inform you that you must eat this notice and ensure that the processing is successful, but you don't have to deal with it when I notice you. Such an operation is obviously possible with another task.

Four, the use of distributed transactions note the following points

1: Ensure that the machine involved in the transaction opens the distributed transaction support;

2: If machine opens the firewall, the MSDTC process needs to be set as an exception;

3: The machine participating in the transaction can not cross the domain (if the cross-domain, currently Microsoft has no exact solution);

4: Distributed transactions are used for multiple databases, preferably sqltransaction if the same database is used.

V. TransactionScope transaction level

The default transaction level in TransactionScope is serializable, which is the complete lock table in the transaction process. Other processes can not query, modify, add, delete. This results in a significant reduction in efficiency, although data integrity is high. Usually we don't need that high data integrity. Therefore, the default transaction level needs to be modified:

All the transaction levels are as follows


Chaos

You cannot overwrite a pending change in a transaction with a higher isolation level.


ReadCommitted

You cannot read mutable data during a transaction, but you can modify it.


ReadUncommitted

Variable data can be read and modified during a transaction.


RepeatableRead

Variable data can be read during a transaction, but cannot be modified. You can add new data during a transaction.


Serializable

You can read mutable data during a transaction, but you cannot modify it, and you cannot add any new data.


Snapshot

Variable data can be read. Before a transaction modifies data, it verifies that the data has been changed by another transaction after it originally read the data. If the data has been updated, an error is raised. This enables the transaction to obtain the previously committed data value.

When you attempt to promote a transaction created at this isolation level, a invalidoperationexception is raised and an error message is generated, "Transactions with IsolationLevel Snapshot cannot is Promoted "(Cannot promote a transaction with a IsolationLevel snapshot).


Unspecified

You are using a different isolation level than the specified isolation level, but this level cannot be determined. If this value is set, an exception is thrown.

Vi. using the TransactionScope class (Distributed Transaction) in C #, be aware of the following considerations

1. Reference the using System.Transactions namespace in the project (first to add a reference to the net component);

2. Set the MSDTC component:

In Control Panel---> Management tools---> services, open the Distributed Transaction Coordinator service.


A, Control Panel, management tools, Component Services, computers, my Computer, right-click Properties
B. Select the MSDTC page and confirm "use local coordinator"
C, click on the "Security Configuration" button below

D, check: "Allow network DTC Access", "Allow remote clients", "Allow inbound", "Allow Outbound", "Do not require authentication".
E, for the database server side, you can select "Require caller Authentication"
F, tick: "Enable transaction Internet Protocol (TIP) transactions."
G. Add MSDTC.exe exceptions in both firewalls
Available command line: netsh firewall set allowedprogram%windir%/system32/msdtc.exe MSDTC enable

3. Restart the IIS server.

Attention:

We just need to make sure that the open operation of the database is open within the scope of the transaction. This enables the correct operation of the transaction.

If the Web server and database are on the same server, TransactionScope is using a local transaction, you do not need to configure MSDTC.

If the Web server and database are not on the same server, TransactionScope will automatically elevate the transaction level to distributed transactions, then MSDTC will need to be configured.

Vii. Examples of TransactionScope

C # codeCopy
        /**/<summary>//Send a message///</summary>//<param name= "Senduserid" ></param> <param name= "Touser" > Format 7ffa3af2-e74b-4174-8403-5010c53e49a7|username, 7ffa3af2-e74b-4174-8403-5010c53e49a7|username</param>//<param name= "content" ></param>/  <param name= "Sendedstatus" > means sent </param>//<returns></returns> public static int         SendMessage (String Senduserid, String touser, string content, String sendedstatus){int receivecount = 0;            Transactionoptions transactionoption = new Transactionoptions ();            Set TRANSACTION ISOLATION Level transactionoption.isolationlevel = System.Transactions.IsolationLevel.ReadCommitted;            Set the transaction timeout time to 60 seconds transactionoption.timeout = new TimeSpan (0, 0, 60);             using (TransactionScope scope = new TransactionScope (transactionscopeoption.required, TransactionOption)){try {//To implement transactional work here//Send Message Insertmessage ( Senduserid, Touser, Content, sendedstatus); Inserting records in the receiving information table Receivecount + = Insertreceivemessage (Userids[0], Senduserid, content, "0"); No error, COMMIT transaction scope.complete (); } catch (Exception ex) {throw new Exception ("Send Message exception, Reason:" +ex. Message); }finally{//release resource scope. Dispose (); }} return receivecount; }

When it comes to business, everyone will think of using transactions in stored procedures, which guarantees data consistency when working with multiple tables. However, many of the methods of Tier D in the three-tier architecture are for single-table operations, and the corresponding database-stored procedures generally involve only a few closely related tables. But when our B-tier business needs to operate on many tables, it is not flexible enough to use stored procedures to ensure transactional flexibility. So how can you use things on level B?

I have been surfing the internet for a lot of information, mostly using sqltransaction to ensure transactional in program code, but SqlTransaction is a class related to SQL Server database, and if this class is used on layer B, it breaks the bottom line of the three-tier architecture. If you change databases in the future (for example, from SQL Server to Oracle), the D and B tiers will have to be rewritten, so there is a lot of limitations.

Later on, I found a lightweight class of things like TransactionScope, a class that is not related to a specific database, and uses this class to ensure that B-level transactional is very feasible.

Let's talk about the basic usage of this class

The default transaction level in TransactionScope is serializable, which is the complete lock table in the transaction process. Other processes can not query, modify, add, delete. This results in a significant reduction in efficiency, although data integrity is high. Usually we don't need that high data integrity. Therefore, the default transaction level needs to be modified:

Change the level of things by Transactionoptions class

[CSharp]View Plaincopy
    1. transactionoptions option = new Transactionoptions ();
    2. Option. IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;

Then use option as the parameter of the TransactionScope constructor to build a lower level TransactionScope object.

[CSharp]View Plaincopy
    1. using (transactionscope scope=new transactionscope (transactionscopeoption.required,option))   
    2. {  
    3.       // Here are several methods    that need to ensure transactional;
    4.         
    5.       if (method execution succeeded)   
    6.       {  
    7.              scope.complete (); //commit transaction   
    8.       }  
    9. }&NBSP;&NBSP;

Note: Successful execution of the method can be judged by the return value of the method, because the B layer calls the D-Layer method to return the general bool value, so as long as all the method return value is True, then the transaction can be committed, otherwise the transaction will not be committed, the code in the using is equivalent to not being executed

Use of TransactionScope

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.