I am using c# .net
I have a POST method in my controller that gets called very quickly by a client. This method gets run concurrently by MVC nature.
[HttpPost]
public IActionResult PostDog(){
AddDog(TempData, new Dog());
return Json("success");
}
That method calls another method that need to have a critical section.
public bool AddDog(ITempDataDictionary tempData, dog){
/* critical section */
List<Dog> dogs = (List<Dog>)(tempData["myDogList"];
dogs.Add(dog);
tempData["myDogList"] = dogs;
/* end critical section */
return true;
}
If the critical section is run parallel, it will will result is lost data.
Is there a way I can implement a critical section using this MVC structure?
*edit - to clarify why the Post Method can be run concurrently:
The method PostDog Can be run concurrently because if a client submits a form or something multiple times very quickly (eg. 10x per second), then the Server will process those Post requests as they come in parallel, instead of making the last request wait to start until all the previous ones are completed.
*edit 2
It looks like using a lock solved my concurrency Issues, but it seems like TempData is not getting updated. Perhaps it has to do with how TempData gets passed to AddDog...
private static readonly object TempDataLock = new();
public static bool AddDog(ITempDataDictionary tempData, dog){
lock(TempDataLock )
{
/* critical section */
List<Dog> dogs = (List<Dog>)(tempData["myDogList"];
dogs.Add(dog);
tempData["myDogList"] = dogs;
/* end critical section */
}
return true;
}