A, lock keyword description
1. lock key block of statements is marked as critical section, the object is to obtain a given mutex statement is executed, and then releases the lock.
2. lock statement block lock function equivalent to
- Monitor.Enter(obj);
- // snippet
- Monitor.Exit(obj);
3. lock to lock a block of statements and Monitor thread locks can not be cross-process synchronization
lock
Keywords can ensure that when a thread is located in a critical area code when another thread does not enter the critical region. If another thread attempts to enter the lock code, it will have to wait (ie stop) until the object is released.
Thread This section discusses the thread.
lock
Keyword call at the beginning of the block the Enter , while calling at the end of the block Exit . ThreadInterruptedException triggered, if Interrupt interrupt latency input lock
thread statement.
Typically, to avoid locking public
type, instance or beyond the control of the code. Common structure lock (this)
, lock (typeof (MyType))
and lock ("myLock")
violation of this guideline:
-
If the instance can be public access, there will be
lock (this)
problems. -
If you
MyType
can be public access, there will belock (typeof (MyType))
problems. -
Since the process used in any other code the same string will share the same lock, so there are
lock("myLock")
problems.
Best practice is to define private
the object to lock, or private static
object variable to protect data common to all instances.
In lock
the text of the statement can not be used to wait for the keyword.
1.lock statement must be locked object reference type, not a value type
2. To avoid deadlocks, lock the target object needs to be private
3. In order to avoid the uniqueness lock object, the lock object through private static or private readonly static
Fourth, use the sample
- private readonly static object _MyLock = new object();
- // lock is recommended for static private static variable
- //private readonly object _MyLock = new object();
- /// <summary>
- /// transactions, multi-table modification
- /// </summary>
- /// <param name="name"></param>
- /// <returns></returns>
- public bool UpdateName(string name)
- {
- lock (_MyLock)
- {
- using (var tran = new TransactionScope())
- {
- ModuleOperate _module = new ModuleOperate();
- // 1. Modify module name
- _module.UpdateFirstName("模块:" + name);
- // 2. Modify menu
- this.UpdateFirstName("菜单:" + name);
- // commit the transaction
- tran.Complete();
- }
- }
- return true;
- }