Reputation: 2143
I have a ASP.NET application where I use a sequence number from a database sequence when creating a record in a table with entity framework. I have a stored procedure that retrieves the next value in this sequence that is called from entity framework and I want to ensure that this retrieval is thread-safe.
I used this answer to attempt this in the following class:
public static class SequenceNumber
{
private static object Lock = new object();
public static long Next(Context db)
{
long next = 0;
lock (Lock)
{
next = db.GetNextComplaintNumber().Single().Value;
}
return next;
}
}
Will this ensure thread-safety?
Upvotes: 1
Views: 1174
Reputation: 1128
The Next(...) method will be threadsafe but the db.GetNextComplaintNumber() will not be (unless it is implemented to be). The lock ensures that any thread calling Next(...) will have to wait their turn to run whatever is in the lock statement. However if any other threads have access to the object db then they could effectively call db.GetNextComplaintNumber() without calling the Next(...) method so it would not be protected by the lock statement. If you can guarantee db.GetNextComplaintNumber() is only called in the Next(...) method then you should be safe, otherwise you would want to implement thread safety into the db.GetNextComplaintNumber() method.
Upvotes: 1