Confusion about the lock statement in C#

后端 未结 6 1263
孤独总比滥情好
孤独总比滥情好 2020-12-05 18:27

This is from MSDN: The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical sectio

6条回答
  •  抹茶落季
    2020-12-05 19:08

    You put a lock on an object. If another thread tries to access a critical section marked by that object at the same time, it will block until the lock is removed/complete.

    Example:

    public static object DatabaseLck= new object();
    
    lock (DatabaseLck) {
            results = db.Query(query).ToList();
         }
    

    Or

    lock (DatabaseLck) {
           results = db.Query(string.Format(query, args)).ToList();
      }
    

    Neither one of those code blocks can be run at the same time BECAUSE they use the same lock object. If you used a different lock object for each, they could run at the same time.

提交回复
热议问题