Use TransactionScope for Distributed Transaction coordination

Source: Internet
Author: User

// The scenario is coordination between multiple databases.. NET 2.0 uses a new type of TransactionScope for coordination, which is more convenient than the previous COM + coordination.

// You need to reference a new assembly: System. Transactions
// Pay special attention to the fact that the transaction isolation level used by TransactionScope by default is serialized, which may be too strict. Therefore, make necessary adjustments as needed.

// Note: MSDTC service support is still required. Enable it with net start msdtc

TransactionOptions options = new TransactionOptions ();
Options. Timeout = new TimeSpan (0, 0, 60 );
Options. IsolationLevel = IsolationLevel. ReadCommitted;
Using (TransactionScope scope = new TransactionScope (options )){

Try
{
SqlConnection conn1 = new SqlConnection ("server = (local); database = demo; integrated security = true ");
Conn1.Open ();
SqlCommand cmd1 = conn1.CreateCommand ();
Statement 1.commandtext = "insert into Table1 VALUES (3 )";
Statement 1.executenonquery ();
SqlConnection conn2 = new SqlConnection ("server = (local); database = northwind; integrated security = true ");
Conn2.Open ();
SqlCommand cmd2 = conn2.CreateCommand ();
Optional 2.commandtext = "drop table Table1 ";

Listen 2.executenonquery ();

Scope. Complete (); // submit distributed transactions

}
Catch (SqlException ex)
{

MessageBox. Show (ex. Message );
}

}

 

Note: TransactionScope does not need the so-called Rollback. As long as there is no Complete, it will automatically Rollback when the using statement block jumps out.

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.