多线程lock(instance)中instance的选择.

时间:2023-03-09 17:31:24
多线程lock(instance)中instance的选择.

如我的提问:http://bbs.****.net/topics/390496351?page=1#post-394837834

拥有类原子功能的类:

class ShareState {  //原子功能.
private object _shareState = new object(); //用于锁定线程.
private int _state = ; public int State {
get { return _state; }
} public int IncreaseState() {
lock(_shareState)
return ++_state;
}
}

MSDN:http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(LOCK_CSHARPKEYWORD)%3bk(TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV4.0%22)%3bk(DevLang-CSHARP)&rd=true

/*所以说,
general, avoid locking on a public type, or instances beyond your code's control. The common constructs lock (this), lock (typeof (MyType)), andlock ("myLock") violate this guideline:
lock (this) is a problem if the instance can be accessed publicly.
lock (typeof (MyType)) is a problem if MyType is publicly accessible.
lock("myLock") is a problem because any other code in the process using the same string, will share the same lock.
Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.
*/