Lock only if value is same?

后端 未结 2 1266
离开以前
离开以前 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:32

    As you want to improve performance, you should make locking at the recent moment as possible. As you use database, you can use DB locking. You got two options:

    1. Use Select for update, look at Proper way to SQL select and update
    2. Use optimistic locking which is IMHO best approach to do that, http://en.wikipedia.org/wiki/Optimistic_concurrency_control or http://docs.jboss.org/hibernate/orm/4.0/devguide/en-US/html/ch05.html

    Note that both approaches allows you to use DB resources more than programmatic ones. This is better more that proposed dictionary, why?

    Once you will duplicate data, those in DB are duplicated in the runtime dictionary, you are forced to sync them, so if someone updates database and add new id you need to immediately update dictionary.

    Sure, it's doable for small maintaining (e.g. repository) class but once your project gets grow, some of your colleague can forget this information and you will start to find such kind of bugs.

    0 讨论(0)
  • 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<long, object> dictionary = 
            new ConcurrentDictionary<long, object>();
    
        private void EditCheck(long checkid)
        {
            var key = dictionary.GetOrAdd(checkid, new object());
            lock (key)
            {
                //Do stuff with key
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题