I do payment online system with asp.net mvc1.0, how can I do to allow only one person to buy something when it's stock is only one. In addtion I use other payment system(like ebay ) in this system.I mean whe开发者_开发知识库n one product's stock is only one, and more than one person to buy it at one moment, how can i do to allow one person can buy it success and other can not buy it any more.
You will probably need to use database transactions to process your orders. It isn't just about locking an object (which, in this case, would have to be a static object in order to be shared by all web users), but about the access to complete an order in its entirety. Transactions are going to be what you need to use.
Also, it isn't clear when you say "I use other payment in this system." That doesn't have any bearing on the transactional management of inventory for sales.
In Order to only one thread to have access to crticial method you could use Lock keywork.
lock (myObj)
{
}
if you are looking for something more then would need more context to understand it.
You need to add a concurrent access control to your system. For example you can implement this simple algorithm:
- Check the quantity of the objects present in the store that you want to sell
- Decrease the quantity for the number of object that you want to sell
- Pay the objects
- if payment is ok then end transaction
- if payment fails then execute the rollback the transaction, increase the quantity and return the money ;)
The important thing is point 2, updating the quantity of element in the store using an optimistic verify algorithm. For example write in the WHERE condition of your SQL operation the value of quantity that you have read in poit 1. If someone change this value the update fails and the sell operation must be interrupted.
精彩评论