Probably Im just stupid but I want to understand how to make thread-safe my operations with db.
For example, I have next code
public async Task<Result> ProcessObjectAsync(long id)
{
SomeObject obj = await _objProvider.GetObjectAsync(id); // gets obj from MongoDB
if (obj.FieldOne == "foo")
{
obj.FieldTwo += 100;
obj.FieldOne = obj.FieldTwo >= 1000 ? "stop" : "bar";
}
else if (obj.FieldOne == "bar")
{
obj.FieldThree += 222;
obj.FieldOne = "foo";
}
Result res = new()
{
Name = obj.FieldOne,
Sum = obj.FieldTwo + obj.FieldThree
};
await _objProvider.SaveObjectAsync(obj); // saves modified object to MongoDB
return res;
}
_objProvider
just some class that simply gets and sets objects in MongoDB
I need to make this code thread-safe, because now it is possible that two requests received in similar time can execute code in one block two times because updated object still not in the db
I see examples with transactions but in all examples they show just very basic CRUD things like “updating object with new data without using current state (fetching it)” but I need to know state of object, so firstly I need to fetch it, do some modifications and after that save it. I need to write some “lock system” around it or I just doesn’t understand how I can use database mechanisms for thread-safety even for those non-basing operations
I will be great if you provide me some examples how to do such things atomically or thread-safe