Came to ask the community for help. I have an API endpoint that will handle saving user favourite items. Due to end system limitation, user data needs to be saved(fav item added/removed), before next favourite item is processed. But on the front end obviously can trigger multiple request if user quickly clicks on different items. And this is where it fails as backend cannot have one user data opened by multiple threads. Been looking into solution with Lock, but no luck. to confirm this was the issue I've added Thread.Sleep() to first method and with that it is working. (well, unless user clicks 3rd time). This is obviously a wrong solution.
Q: How can I pause a method (that handles user saving) until the previous one for the user is completed?
Just to clarify I can have user1,user2,user3 making request at the same time. that is not a problem. Issue is if I have user1 making 2-3 request (e.g. to remove ItemA, add ItemB, remove ItemC) as front end would enable to do so - and that is not changing.
public class ApiController{
//called from frontend
[HttpPost]
[Route("toggleUserFavourites/")]
public async Task<HttpResponseMessage> toggleUserFavourites(FavouriteData data)
{
//here is just testing theory that this is actually wrong. If I wait all works fine.
if(currentRequest.Contains(data.userId)){
Thread.Sleep(6000);
}
currentRequest.Add(data.userId);
return await toggleUserFavouritesHandleEntry(data);
}
//Handle user saving data
public async Task<HttpResponseMessage> toggleUserFavouritesHandleEntry(FavouriteData data){
//CODE THAT TALKS TO BACKEND TO GET EXISTING USER DATA AND awaits response - 2-4 secs
try {
user.Save();
var response = Request.CreateResponse(HttpStatusCode.OK);
return Request.CreateResponse(HttpStatusCode.OK, "User updated ");
}
catch (Exception ex){
return Request.CreateResponse(HttpStatusCode.Forbidden, "Error saving");
}
}
for reference
public class FavouriteData{
public string userId {get; set;}
public string itemId {get; set;}
}