On Sun, 17 Aug 2008 21:49:28 -0700, CKKwan <ck****@my-deja.comwrote:
Dear All,
[Synchronization]
Can synchronize a class, any function is called and the entire class
is locked.
No, not at all. That attribute is used for remoting. I admit, I'm not
completely sure of the details, but I can guarantee you that it doesn't
lock "an entire class". I wrote a small test program and confirmed that
multiple threads can still access members of a given class simultaneously
even with that attribute applied to the class.
It appears to me that it handles synchronization across remoting contexts,
whatever those are. It probably ensures synchronization/consistency
across multiple remoting endpoints. But whatever it does, it's definitely
not a general-purpose synchronization mechanism.
[MethodImplAttribute(MethodImplOptions.Synchronized )]
Can synchronize a method
No, not precisely. Synchronizes _all_ such labeled methods in a class,
along with anything that explicitly uses the type (when applied to static
members) or instance (when applied to instance members) for locking.
What if I need to Lock a class only when specific method is call?
I'm not convinced the question makes sense. See below...
For Example:
public class C
{
public void A() {}
public void B() {}
}
The instance of class C need to be locked when method B() is called,
but not lock when method A() is called.
What does it mean to lock "the instance", if you don't want method A() to
participate in the locking? If A() doesn't participate, then at least
some of the instance (i.e method A()) doesn't wind up locked. You can
lock "on the instance", but I wouldn't say that's the same as locking
"_the_ instance".
Certainly I can manually put 'lock(this)' in method B(). But is there
any other way of doing this?
Putting a "lock(this)" in method B() would have the effect of
synchronizing method B() and any other code that is also protected by
locking on the instance. That is, only one thread could be executing any
of those at once.
If that's the effect you want, then why not use that approach? If it's
not the effect you want, then maybe you can try to be more clear about
what effect you do want.
Pete