From theory to practice (12): transactions

Source: Internet
Author: User

Purpose

By reading this article, you can learn about the following:

1) how to implement transactions in WCF?

2) Talk about the knowledge of transaction isolation

3) What kind of resistance will transaction implementation bring to programming?

4) How does WCF implement distributed transactions?

5) the code is not a lie. Use a deposit and withdrawal example to practice the WCF transaction.


This article is suitable for readers

This article is suitable for beginners of WCF. Before learning this article, you 'd better read the first few articles in the theory-to-practice series of WCF.


How to Implement transactions in WCF?

Transactions are originally hard to implement. However, WCF can always be used as a magic means. It can implement distributed transactions through simple declarative programming, let's take a look at the hero of achieving this goal:
 
1) transactionflowattrioption: an attribute of the OperationContractAttribute, which can indicate the transaction option (TransactionFlowOption) of the Operation ).

2) TransactionFlowOption: it is a parameter in the TransactionFlowAttribute constructor and is an enumeration (enum). It includes three enumeration items NotAllowed: transactions not Allowed, default values; Allowed: transactions Allowed, this means that the transaction is dispensable. Mandatory: a Mandatory transaction, indicating that the transaction is required.

3) TransactionAutoCompleteOnSessionClose: it is an attribute of OperationBehaviorAttribute. It is used to indicate whether the server instance is automatically released after the transaction is completed. This attribute is closely related to the instance mode of the service object, when using it, you should pay attention to it, which will be explained below.

4) TransactionIsolationLevel: it is also an attribute of OperationBehaviorAttribute, used to indicate the isolation level ). five options: Any, ReadUncommitted, ReadCommitted, RepeatableRead, Serializable, and transaction isolation methods are complex.

5) TransactionTimeout: it is also an attribute of OperationBehaviorAttribute to indicate the transaction timeout time. The default value is TimeSpan. zero, indicating that it will not be limited by the timeout period ..: OperationBehaviorAttribute: it is also an attribute of OperationBehaviorAttribute to indicate distributed Transaction options. If it is set to true, it must be within the Transaction range (Transaction Scorp.
 
With the use of the above attributes, we can easily implement transactions and distributed transactions in WCF. For specific implementation methods, refer to the sample code.


About how to isolate transactions

Simple transactions have the following three problems:

1) Dirty read: Simply put, the transaction changes the data at a certain time point. The changed data is read by transaction 2, but transaction 1 eventually fails, as a result of data rollback, transaction 2 is a victim.

2) Non-reproducible reading: The results of each read of the same data are different, that is, non-repeatable reading. For example, transaction 1 changes the data to be read and this is non-reproducible read.

3) Phantom read: It is very simple. For example, when a transaction is in the data query, but transaction 2 inserts a data that meets the query conditions, this will lead to the Phantom read of the newly inserted data.

The explanation of the three problems may be difficult to understand. In short, dirty reading reads read the data that someone else is changing, and repeated reading changes the data that others are reading, however, phantom read reads data that has not been inserted, modified, or deleted by others, which is much easier to understand.

For the preceding problems, you can set different isolation methods for transactions to prevent them from occurring. The isolation methods for transactions include:

1) Any: the isolation level of the component is obtained from the isolation level of the called component. If the component is a root component, the isolation level is used in Serializable.

2) ReadUncommitted: Read uncommitted data. This mode keeps share lock when reading data to avoid reading modified data, but you can change the data before the transaction ends, this causes non-repeatable reading or phantom reading.

3) ReadCommitted: Read committed data, issue a share lock, and allow non-exclusive locking. This method is similar to reading uncommitted data. This method seems similar to reading uncommitted data, but there is a difference that the read-only lock of the transaction will be unlocked when it is moved to the next row, the write lock is unlocked only after the transaction is completed or aborted, and the transaction has to wait for all the write locks to be unlocked.

4) RepeatableRead: reads data repeatedly. Similar to reading committed data, lock all data used in the query to prevent other users from updating the data. Prevents non-repeated reads, but Phantom read rows may still occur. The read-only lock can be released only after the transaction is completed or aborted.

5) Serializable: prevents update or insertion before the transaction is completed.

As described above, several isolation methods are difficult to distinguish, but they can solve different problems faced by transactions. Remember these methods to better understand isolation methods.

Isolation level

ReadUncommitted

ReadCommitted

RepeatableRead

Serializable

Dirty read

Yes

No

No

No

Non-reproducible reading

Yes

Yes

No

No

Phantom read

Yes

Yes

Yes

No

From the table above, we can see that apart from Any, the isolation method is more rigorous than level 1. Any is in the same line. If it has no inheritance, it will be the strictest Serializable.


What kind of resistance will the implementation of transactions bring to our programming?

1) specify TransactionFlow (TransactionFlowOption. mandatory), but the Binding does not set TransactionFlow to true. In this case, at least one operation similar to the "Bank" protocol is configured to set the TransactionFlowAttribute attribute to "force ", however, the channel binding "WSDualHttpBinding" does not use TransactionFlowBindingElement for configuration. No TransactionFlowBindingElement is available. You cannot use the TransactionFlowAttribute attribute set to "forced. This error message.

 
2) If the [OperationBehavior (TransactionScopeRequired = true)] operation is set, but it is not executed in TransactionScorp, an exception similar to "service operation requires transaction to be a stream" will occur, as shown below:

3) maybe both of the above problems are not a problem, so we need to pay attention to this point, otherwise we will suffer a lot. This involves the connection between transactions and service instance models.From theory to practice: instance mode and object Lifecycle We have learned that the instance will not be created and extinct every time in the PerSession or Single mode. This is indeed an indisputable truth, but it is challenged here. You can write a program, that is to say, you can use the most reassuring Single mode. At that time, it is not to say that the service instance is created once and is used for life? Next let's take a look at the running results after I first compiled the sample program.

However, during the call, I found a very strange problem. Theoretically, the Bank service instance should be created only once, but it can run as follows:

 

Is this result disappointing? This is because the service that implements the transaction must be subject to the restriction of TransactionAutoCompleteOnSessionClose. This attribute is set to true by default, which indicates that WCF forcibly destroys the service instance after the transaction is completed, it is equivalent to calling the Dispose () method of the service for release, even if it is a PerSession or Single, it is hard to escape its legal network. If you want to maintain the instance mode, you can set it to false. After the change, the running effect will not be provided as expected.

4) in this article, more distributed tasks are implemented, and the TransactionScrop class is used for distributed tasks. For some precautions about this class, refer to my previous article:Comparison of Two transaction methods

How does WCF implement distributed transactions?

The basis for implementing transactions in WCF is based on the WS-AtomicTransaction standard. The underlying things should belong to the XXX insider series. This article will not elaborate in detail. If you are interested, you can view several articles by Kevin Li's brother in the garden. I will list them below. I hope Kevin Li will not be surprised.

1)WCF remote distributed transaction based on WS-AtomicTransaction (1)

2) WS-AtomicTransaction-based WCF remote distributed transaction (2)

3) WS-AtomicTransaction-based WCF remote distributed transaction (Supplement)

The code is not a lie. Use a deposit and withdrawal example to practice the WCF transaction.

A small example is created to demonstrate the transaction implementation. The example is as follows:

There are two services: 1) iatm server: it is a service that simulates the ATM machine of a bank 2) IBank, it simulates the account service of a bank. To create a client to simulate an ATM, follow these steps:

1) Plug-in card

2) Deposits

3) Withdrawal

4) card pulling

The operation is relatively simple. Do not repeat it. Note that when the withdrawal amount is greater than the balance, the system will hold an error while the account balance will not be changed. Run

Project source file:/Files/jillzhang/Jillzhang.Wcf.DistributedTranscations.rar


References

1) http://www.rainsts.net/article.asp? Id = 479

2) http://blog.csdn.net/honkerhero/archive/2007/03/30/1546429.aspx

3) http://www.rainsts.net/article.asp? Id = 443

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.