GregInWI2
GregInWI2

Reputation: 904

ASP.NET Race Conditions

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.

Upvotes: 2

Views: 2381

Answers (2)

Russ Cam
Russ Cam

Reputation: 125538

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.

private static someObject = new Object();

public void SomeMethod() 
{
    lock(someObject) 
    {
        // do something with your shared resource.
    }

}

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.

Upvotes: 5

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

You could decorate it with the [MethodImpl] attribute:

[MethodImpl(MethodImplOptions.Synchronized)]
public static void SomeMethod()
{
    ...
}

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.

Upvotes: 3

Related Questions