Lock only if value is same?

后端 未结 2 1265
离开以前
离开以前 2020-12-06 05:54

If i have an function that edits the database in my webservice that i only want one thread to execute at one time if they try to edit the same row.

void Edit         


        
2条回答
  •  自闭症患者
    2020-12-06 06:40

    You can use a ConcurrentDictionary to map each id to an object that you can lock on:

    public class Foo
    {
        private ConcurrentDictionary dictionary = 
            new ConcurrentDictionary();
    
        private void EditCheck(long checkid)
        {
            var key = dictionary.GetOrAdd(checkid, new object());
            lock (key)
            {
                //Do stuff with key
            }
        }
    }
    

提交回复
热议问题