ASP.NET 竞争条件
防止两个不同的人同时执行同一个方法的最佳方法是什么?例如,用户 A 与用户 B 位于同一页面。两人同时按下页面上的按钮,并执行该事件的代码。我试图让一个人等待另一个人完成。
有一个通用的方法可以做到这一点吗?
这里有一些更多信息..
这是一个简单的游戏,您可以在其中购买网站会员(例如 FB 上的 Owned 游戏)。查询字符串是用户的 ID。我遇到了两个人同时点击“购买”的问题。一种获得了用户,另一种则只是损失金钱。所以我试图阻止在同一时间购买以阻止这种情况发生。
What's the best way to prevent two different people from executing the same method at the same time? Example, user A is on the same page as user B. Both press the button on the page at the exact same time executing the code for that event. I'm trying to make one wait for the other one to finish.
Is there a common way for doing this?
Here's some more info..
This is for a simple game where you buy members of the site (like the Owned game on FB). The querystring is the ID of the user. I'm having a problem where two people are clicking buy at the same time. One gets the user and the other just loses money. So I'm trying to prevent buying at the exact same time to stop that from happening.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
页面
将为每个请求创建实例,因此假设您拥有的逻辑位于实例成员中并且不访问任何共享的内容,则不需要锁定。如果访问共享资源,有几种方法可以强制锁定。一种方法是使用
锁
语句eg一般来说,您应该尽可能避免使用锁(尽管有很多情况需要锁)。
编辑:
如果您将数据保存在支持事务的数据源中,例如数据库,那么您首先要检查用户尝试购买的商品是否尚未购买用户在页面上单击“是”与您的应用程序收到响应之间的时间。因此,您需要检查数据源以查看是否尚未购买该商品,如果尚未购买,则为用户“购买”该商品。这应该在交易内部完成,以便它是原子的,因此只有在“购买”物品的操作成功时,您才可以从用户的帐户中获取资金。
A
Page
instance will be created for each request, so assuming that the logic you have is in an instance member and does not access anything that is shared, no locking is required.If hitting a shared resource, there are a few ways that you could enforce locking. One way would be to use a
lock
statement e.g.Generally speaking, you should aim to avoid using locks as much as possible (although there are many situations where a lock is required).
EDIT:
If you're holding your data in a data source that supports transactions e.g. like a database, then you would first want to check that what a user is attempting to buy hasn't already been bought in the time between the user clicking "yes" on the page and your application receiving the response. So, you need to check the data source to see if it hasn't already been bought and if it hasn't, then "buy" the item for the user. This should be done inside of a transaction so that it is atomic and therefore you only take money from the user's account if the action of "buying" the item is successful.
您可以使用
[MethodImpl]< 来装饰它/code>
属性:
这样只有一个线程可以执行该方法,其他线程将等待。它相当于给整个方法体加了一个
锁
。You could decorate it with the
[MethodImpl]
attribute:This way only one thread can execute the method and others will wait. It is equivalent to putting a
lock
to the entire method body.