1

I have a website where the frontend auto saves data entered to the backend. It is possible that these saves maybe very close together, and I want to lock the saving of results on a per user basis.

I don't want to use a simple 'lock' as that will block all users trying to save.

Is there anyway to do this in .NET?

4

1 回答 1

4

每个用户都有一个锁定对象听起来很合理。我还建议您使用 Monitor.TryEnter 而不是 lock,如果已经有正在进行的保存,则跳过保存。像这样的东西:

static ConcurrentDictionary<string, object> _locksByUser = new ConcurrentDictionary<string, object>();

public void Save(string userId) {
   var lock = _locksByUser.GetOrAdd(userId, new object());
   if (Monitor.TryEnter(lock)) {
       try {
       //do save here
       }
       finally {
           Monitor.Exit(lock);
       }
   }
}
于 2013-10-26T03:29:51.363 回答