Is it possible to use a Lock-method "per (web)session"?

25 Views Asked by At

i'm sorry for my lack of english:

I have a web app that allows users to adjust their preferences on the homepage. The homepage contains, for example, 3 fields: "Google," "YouTube," and "Stack Overflow." The user has the option to move or hide these fields on the main page to save their preferences. Now, a strange bug has crept into the program causing it to save a preference twice in the database, where only one should be. I have debugged and found that this happens in the code below because the function call hasn't been completed yet, so a new one starts and thus two preferences are saved instead of one or that one being overwritten. Is there a way to, let's say, provide some kind of lock in this code where only the logged-in user locks themselves until the function is done? So that they don't disturb other users?

[HttpPost] public ActionResult Index(string prefs) { int uid = User.Identity.Id();

 lock (prefsLock)
 {
     // Save user preferences
     UserPrefs prefsInDb = db.UserPrefs.SingleOrDefault(p => p.UserId == uid);
     if (prefsInDb != null)
     {
         // Update existing entry
         prefsInDb.Preferences = prefs;
         db.Entry(prefsInDb).State = EntityState.Modified;
     }
     else
     {
         // Add new preferences entry
         UserPrefs up = new UserPrefs()
         {
             Preferences = prefs,
             UserId = uid,
         };
         db.UserPrefs.Add(up);
     }

     db.SaveChanges();
 }

 return Json(new { });

}

as you can see I've tried it with a normal Lock, problem is that this locks every user that tries accessing the function. I want the user to only Lock himself until the entry has been made.

0

There are 0 best solutions below