Manvinder
Manvinder

Reputation: 4587

Lock object based on a condition in c#

I need to lock a piece of code based on the value of a variable or a property. Assume my method is being called and pass UserData object.

UserData contains two properties 

UserID and Marks

And the lock code currently is like

var l=new Object();
lock(l)
{
//Update marks of a particualr user id to UserData.Marks
}

Now it'll lock everything that comes for this method, Say it is updating marks of UserID=1, it'll still lock the future calls of other User IDs, I want it to lock requests for that particular user id which is accessing the lock, in this Case User 1. Other should move freely.

What I was thinking that rather create an new object for locking, create a custom class for lock which contains the property of User ID. When the request comes I create a lock based on that particular value. I don't even know if this is possible. Kindly guide me in correct direction.

Upvotes: 1

Views: 1903

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127553

The way you are currently locking would not do anything at all as two threads calling the function would create two seperate lock objects, however you stated "Assume my method is being called and pass UserData object." and also that each UserData object just has the two properties of Id and Marks

If that is true, all you need to do is lock on that UserData object.

public void UpdateMarks(UserData userData)
{
    lock(userData)
    {
         //Do stuff to userData.Marks
    }
}

The only thing to be aware of is if you have further locks inside that code that could depend on other lock objects you could get your self in to a deadlocked situation.

Upvotes: 2

Related Questions