Let’s say I have two methods –
getCurrentValue(int valueID)
updateValues(int changedComponentID)
These two methods are called on the same object independently by separate threads.
getCurrentValue() simply does a database look-up for the current valueID.
“Values” change if their corresponding components change. The updateValues()method updates those values that are dependent upon the component that just changed, i.e. changedComponentID. This is a database operation and takes time.
While this update operation is going on, I do not want to return a stale value by doing a lookup from the database, but I want to wait till the update method has completed. At the same time, I don’t want two update operations to happen simultaneously or an update to happen when a read is going on.
So, I’m thinking of doing it this way –
[MethodImpl(MethodImplOptions.Synchronized)]
public int getCurrentValue(int valueID)
{
while(updateOperationIsGoingOn)
{
// do nothing
}
readOperationIsGoingOn = true;
value = // read value from DB
readOperationIsGoingOn = false;
return value;
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void updateValues(int componentID)
{
while(readOperationIsGoingOn)
{
// do nothing
}
updateOperationIsGoingOn = true;
// update values in DB
updateOperationIsGoingOn = false;
}
I’m not sure whether this is a correct way of doing it. Any suggestions? Thanks.
That’s not the correct way. Like this you are doing an “active wait”, effectively blocking your CPU.
You should use a lock instead: