lock inside lock

后端 未结 3 1981
挽巷
挽巷 2021-02-06 20:16

I\'m wondering if this construction will cause an error:

lock(sync)
{
  // something
  lock(sync)
  {
    //something
    lock(sync)
    {
      //something
             


        
3条回答
  •  盖世英雄少女心
    2021-02-06 20:55

    To explain why it is well-defined behavior and will never fail:

    Aside: This answer has better details about how locks actually work

    The lock occurs at the Thread level, so calling it a second time on the same thread will be redundant. I would think it would not have any performance penalty (although that would depend on how exactly the internals of .Net are written, so I can't guarantee that)

    Many times you'd have a public function that calls another public function in your class, whom both need the lock when used seperately. If this was not allowed the following would fail:

    private Dictionary database = new Dictionary();
    private object databaseLock = new object();
    public void AddOrUpdate(string item)
    {
        lock (databaseLock)
        {
            if (Exists(item))
                database.Add(item, 1);
            else
                ++database[item];
        }
    }
    public bool Exists(string item)
    {
        lock (databaseLock)
        {
            //... Maybe some pre-processing of the key or item...
            return database.ContainsKey(item);
        }
    }
    

提交回复
热议问题