Understand transactions in. NET 2.0

Source: Internet
Author: User
Tags microsoft sql server 2005 msmq connectionstrings

In fact, all commercial applications require transaction support at different levels. Using the architecture rules provided by relational databases, the complete data can be displayed in a static view to a large extent. However, in a dynamic process, the transaction can ensure that the application or not all the changes at the end of the persistence process. This article focuses on the transaction functions provided by. NET 2.0. First, it introduces the concept of transactions and database transactions, and then explains the transaction functions in. NET 2.0.

1. Transaction concept sxoc = *) q | kfp5 [} QB! [This material comes from your state learning network programming. Net tutorial http://Www.gzU521.com] sxoc = *) q | kfp5 [} QB!

To understand. Net's support for transactions, it is important to establish an overall understanding of transactions. Transactions ensure the implementation. Unless all operations are successfully completed, the resources facing data will not be updated persistently. Transactions are defined by a group of successful or failed operations. That is to say, if all operations in the transaction are successfully completed, commit the transaction and write the updated data persistently. However, if one of the operations fails, the rollback is performed, and the result data is returned to the status before the transaction starts. For example, assume that you want to transfer RMB 100 from account A to account B. This operation involves two steps: (1) deduct 100 yuan from account. (2) Add 100 yuan to account B. If Step 1 is successfully completed, but step 2 fails due to some reasons. If Step 1 is not restored, the entire operation will be incorrect. Transactions can help to avoid this situation. If all the steps are successful, the operations in the same transaction will modify the database. In this example, if Step 2 fails, the changes caused by the step will not be submitted to the database.

Generally, transactions follow specific rules, which are called ACID properties. Acid ensures that complex transactions are self-contained and reliable. The following is a brief introduction to this feature.

Transactions must have atomicity, consistency, isolation, and durability ). The first letter of these four features is acid. Although acronyms are easy to remember, the meaning of each word is not obvious. The following is a brief description:

Atomicity: atomicity ensures that either all updates are executed or nothing happens. Due to the atomicity guarantee in the transaction, developers do not have to write code to handle a successful update, but the other fails.

Consistency: Consistency means that the transaction results keep the system consistent. Data remains valid before the transaction starts, just as at the end of the transaction. Consistency also ensures that the transaction must keep the database in a consistent state. If some operations of the transaction fail, the other parts must return to the original state.

Isolation: multiple users may access the same database at the same time. Isolation ensures that data changes in the transaction cannot be seen outside the transaction before the transaction is completed. And cannot access some intermediate states. if the transaction is terminated, these statuses will not occur.

Persistence: Persistence means consistency even if the system crashes. If the database system crashes, durability must ensure that committed transactions are indeed written to the database.

2. database transactions

Transactions are often used in many commercial applications because transactions bring stability and predictability to the system. Generally, data sources are used to store data when developing software systems. To apply the transaction concept in such a software system, the data source must support transactions. Modern databases such as Microsoft SQL Server 2005 and Oracle 9i support transactions. For example, SQL Server 2005 provides some T-SQL statements that support transactions, such as begin transaction, save transaction, commit transaction, and rollback transaction. Data Access APIs, such as ODBC, ole db, and ado.net, enable developers to use transactions in applications. Generally, as long as a single database is used, RDBMS and data access APIs provide transaction support. In many large applications that contain multiple databases, Microsoft Distributed Transaction Processing Coordinator (MSDTC) may be required ). COM + is a popular middleware product. It uses MSDTC internally to help implement multi-database transactions, or even transactions between different known transaction entities, and usually uses it as a resource manager. It should be noted that in. NET 2.0, you can use the system. Transactions namespace to set distributed transactions to replace system. enterpriseservices.

Transactions are classified into local transactions and distributed transactions. (1) local transaction: This type of transaction uses known data sources (such as SQL Server), and is also a single-phase transaction. When a single database stores all transaction-related data, acid rules can be enforced for itself. This means that in a single database server (such as SQL Server), local transactions can be used across databases as long as the same connection is used. (2) distributed transactions: these transactions use multiple known transaction data sources. Distributed behavior may require reading messages from the Message Queue Server, obtaining data from the SQL Server database, and writing messages to other databases.

Some software packages (such as MSDTC) can help implement distributed transactions programmatically. By using some methods (such as two-phase commit and rollback), you can control the commit and rollback actions across all data sources, to ensure integration. MSDTC is only applicable to applications compatible with transaction management interfaces. Currently available applications include MSMQ, SQL Server, Oracle, Sybase, and other currently available applications (called resource manager ).

In a distributed transaction environment, different resource managers need to implement reliable Commit Protocols. The most common implementation is two-phase commit. In two-phase submission, the actual submission is divided into two phases: the first stage includes preparing some required changes for the submission. In this way, the resource manager will communicate with the Transaction Coordinator to inform it that the update preparation is ready and the preparation is executed and submitted, but the actual process is not submitted yet. In the second phase, once all the resource managers inform the Transaction Coordinator that the preparation is ready, the Transaction Coordinator will make all the participants understand that the work is ready and then execute the changes. In two-phase commit, one or more databases can participate in distributed transactions. In fact, any objects registered in MSDTC transactions can participate in distributed transactions managed by MSDTC. For example, MSMQ can participate in transactions that connect two different databases by two sqlconnection objects.

3. Transactions in. NET 2.0

By registering the resource manager of the transaction job type being executed, the transaction management system in. NET Framework 2.0 can solve the extra overhead problem caused by dynamic Transaction combinations. It also provides the architecture required to convert multiple unstable resources into a transaction model for submission and rollback. In the following content, we will introduce lightweight transaction management, explicit transactions, transactionscope classes, and automated transactions related to transactions in. NET 2.0.


 

Lightweight Transaction Management

For transactions that occur in a single application domain, ltm is a very fast and inexpensive resource manager. Ltm is the starting point for all transactions in the framework. It also monitors resources that are interacting with transactions and registers more robust Transaction Manager services as needed.

When transactional work is performed outside of the process (for example, starting to modify Database Data), ltm automatically uses the resource manager model that supports upgradeable single-phase registration (pspe. This is a new transactional architecture that understands ltm's "prepayment" mechanism. If no pspe manager is available, ltm registers DTC. Of course, multiple remote data sources will be modified by the registered DTC. When the pspe model starts to work, the transaction execution will be consistent with the transactions in ado.net 1. X. Readers may suspect that pspe has the same performance as ado.net transactions. When interacting with multiple databases, transactions are automatically upgraded to DTC.

In. NET Framework 2.0, pspe transactions are automatically obtained when SQL Server 2005 is used. If transactional work interacts with another server or database, DTC is automatically used. Nonvolatile transactions are automatically involved in pspe without calling DTC.

Implement explicit transaction EA 'Fr/qlgnt7f ([post to my learning network programming. Net tutorial http://www.Gzu521.com] EA 'Fr/qlgnt7f (

Sometimes, the default implicit automatic transaction function of the transactionscope object may not provide the desired control level. In this case, you may need to manually create a transaction and commit or roll back the transaction explicitly. Example 1 shows the steps involved in creating an explicit transaction using the committabletransaction class.

Example 1: Use committabletransaction to implement explicit transactions

Void btnsave_click (Object sender, eventargs e) {committabletransaction trans = new committabletransaction ();

Try {string connectionstring = webconfigurationmanager. connectionstrings ["mydatabase"]. connectionstring;

Using (sqlconnection connection = new sqlconnection (connectionstring) {string SQL = "insert into production. productcategory (name, "+" rowguid, modifieddate) values (@ name, @ rowguid, @ modifieddate )";

// Open the connection and register the connection. open () in the transaction scope ();

Sqlcommand command = new sqlcommand (SQL, connection );

Command. commandtype = commandtype. text;

Sqlparameter nameparam = new sqlparameter ("@ name", sqldbtype. nvarchar, 50 );

Nameparam. value = txtcategoryname. Text; command. Parameters. Add (nameparam );

Sqlparameter guidparam = new sqlparameter ("@ rowguid", sqldbtype. uniqueidentifier );

Guidparam. value = system. guid. newguid ();

Command. Parameters. Add (guidparam );

Sqlparameter modifiedateparam = new sqlparameter ("@ modifieddate", sqldbtype. datetime );

Modifiedateparam. value = system. datetime. now;

Command. Parameters. Add (modifiedateparam );

// Register the transaction within the scope of the current transaction

Connection. enlisttransaction (trans );

Command.exe cutenonquery ();

// If each execution succeeds, the transaction Trans. Commit () is committed ();

}

Lblresult. Text = "category is written successfully ";

}

Catch (exception ex) {// if an exception occurs, the transaction Trans. rollback () is rolled back ();

Lblresult. Text = "exception is:" + ex. message;

}}

TEXT = "category name:" width = "179px"> onclick = "btnsave_click"/> font-size = "small"/>
 

 

In this method, you need to call the enlisttransaction () method of the sqlconnection object (passing the committabletransaction object as the parameter) to associate the sqlconnection object with the committabletransaction object. Once this is done, you can explicitly commit or roll back the transaction by calling the Commit () and rollback () Methods of the committabletransaction object. As you can imagine, it is not recommended to use this manual method, because when there are different types of exceptions, there may be risks of failure to roll back the transaction.

Use transactionscope class

As the name implies, the transactionscope class is used to limit the transaction code block. It has some obvious advantages, such as the range is irrelevant to the application object model, and provides a simple and intuitive programming model. Within the constructor of this class, the transactionscope object creates a transaction (lightweight Transaction Manager by default in. NET 2.0) and sets this transaction to the current attribute of the transaction class. Because transactionscope is a releasable object, the transaction will call the dispose () method to release the object:

Using (transactionscope scope = new transactionscope () {/* implement transactional work here * // No error -- submit transaction scope. Complete ();}
 

Example 2 lists a method for creating a transaction in. NET 2.0. Create and release the transactionscope object in the code block defined by the transactionscope object. Using the constructor of the transactionscope object and the transactionscospontion enumeration, developers can determine whether new transactions are required or whether transactions that already exist in external blocks should be used. The transactionscope. Complete () method indicates that all operations within the transaction range have been completed successfully. At the end of the using Statement (where the dispose () method is called), the output of the transaction block is defined. If the complete () method is not called due to an exception, the transaction is abandoned. If the transaction is successfully completed within the scope of the transaction, if the transaction is a root transaction, the transaction is committed when the transaction is a root transaction. If the root transaction is not in the range, the transaction output will be affected.

 

 

 

Example 2: Use transactionscope to implement implicit transactions

Void btnsave_click (Object sender, eventargs e) {try {int categoryid; string connectionstring = webconfigurationmanager. connectionstrings ["mydatabase"]. connectionstring; using (transactionscope scope = new transactionscope () {using (sqlconnection connection = new sqlconnection (connectionstring) {categoryid = insertcategory (connection);} // submit the transaction scope. complete ();} lblresult. TEXT = "category is written successfully ***** category id =" + categoryid. tostring ();} catch (exception ex) {lblresult. TEXT = "exception is:" + ex. message ;}} int insertcategory (sqlconnection connection) {}width = "179px"> onclick = "btnsave_click"/> font-size = "small"/>
 

 

In Example 2, the SQL statement inserted for the mydatabase database is included in the transactionscope object using the using block. The insertcategroy () method inserts a new record into the productcategory table. After a record is inserted, this method returns the id value (Category ID column) of the newly inserted record to the caller ). Once the code is successfully executed, the complete () method of the transactionscope object is called to inform that the. NET Framework statement has been successfully executed, and the results of the transaction will be submitted to the database.
 

The following are some of the content completed by transactionscope:

Any statement that appears in using statement brackets will be executed within the transaction scope.
Any connections created in the block will be registered in the transaction.
If an error occurs in the using block, the transaction is automatically rolled back.
If the statement is successfully executed, you need to call the complete () method in the transaction as part of the work.
Each step of the call stack must call complete () to commit transactions.

The transactionscope object does not know whether to submit or discard transactions. The main goal of transactionscope is to avoid direct interaction between developers and transactions. To solve this problem, each transactionscope object has a consistent bit, which is set to false by default. By calling the complete () method, you can set the consistency bit to true. Note that only one complete () can be called (). Subsequent calls to complete () will cause an invalidoperation exception, because after the call to complete (), there cannot be transactional code.

Automatic transactions in Asp.net

By adding the transaction attribute to the Asp.net page, Asp.net can support Automatic transactions in the system. With the transaction attribute, developers can instruct the page to participate in existing transactions, start new transactions, or not participate in transactions. The following table lists the available transaction attribute values in Asp.net.

Source code of the image:

 
Figure 1

You can set the transaction attribute in the page command in the Code to define the transaction level supported by the page. For example, inserting the following command ensures that page activities are always executed within the transaction scope:

Void page_load (Object sender, system. eventargs e) {aborttransaction + = new system. eventhandler (aborttransactionevent); committransaction + = new system. eventhandler (committransactionevent); try {/* put the transactional code here */contextutil. setcomplete ();} catch (exception) {contextutil. setabort () ;}} void aborttransactionevent (Object sender, system. eventargs e) {/* code used for rollback */} void committransactionevent (objectsender, system. eventargs E) {/* code used to submit behavior */} ere6_l "I | U' [This _ 文_lai_source _ Yu _ _ Network programming. net tutorial http://Www.GZU521.Com] ere6_l "I | U'
 

If the transaction attribute is omitted, the transaction is disabled on the page. Use the static method of the system. deleiseservices. contextutil class to submit or discard the transaction on the Asp.net page. These static methods are setcomplete () and setabort () (they correspond to the page event committransaction () and aborttransaction () respectively ()). The following code lists the page implementation framework. This page sets the transaction attribute of the page instruction to required, and writes the Code required to process the transaction result in the committransaction () and aborttransaction () events.

Void page_load (Object sender, system. eventargs e) {aborttransaction + = new system. eventhandler (aborttransactionevent); committransaction + = new system. eventhandler (committransactionevent); try {/* put the transactional code here */contextutil. setcomplete ();} catch (exception) {contextutil. setabort () ;}} void aborttransactionevent (Object sender, system. eventargs e) {/* code used for rollback */} void committransactionevent (Object sender, system. eventargs e) {/* code used to submit behavior */}
 

4. When to use transactions

Although. NET 2.0 provides good support for transactions, it is not necessary to always use transactions. The first rule for using transactions is that transactions should be used when transactions can be used, but should not be used excessively. The reason is that every time a transaction is used, a certain amount of overhead will be occupied. In addition, the transaction may lock some table rows. Another rule is that transactions are used only when operations are required. For example, if you only query some records from the database or execute a single query, explicit transactions are not required in most cases.

Developers should keep a concept in mind, that is, the lengthy transactions used to modify data in multiple different tables will seriously impede all other users in the system. This may cause some performance problems. When implementing a transaction, the following practical experience can achieve acceptable results: (1) avoid using the SELECT statement in the transaction to return data, unless the statement depends on the returned data; (2) if a SELECT statement is used, only the required rows are selected, so that too many resources are not locked and performance is improved as much as possible. (3) write all transactions in T-SQL or API as much as possible; (4) Avoid combining transactions with multiple independent batch processing tasks, and place these batches in separate transactions; (5) Avoid as many updates as possible.

In addition, you must note the default transaction behavior. By default, if no explicit transaction is committed, the transaction will be rolled back. Although the default behavior allows transaction rollback, explicit rollback is always a good programming habit. This not only releases locked data, but also makes the code easier to read and has fewer errors.

5. Summary

The transaction function provided by. NET 2.0 is very powerful, and the specific content is far more simple than described in this article. This article is just a fascinating feature. It is hoped that the reader can use the transaction function flexibly and appropriately, instead of using the transaction in the past, otherwise it may play a negative effect on performance.

(Www.gz u521.com), original address: http://www.gzu521.com/campus/article/program/200802/165188_3.htm

 

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.