Vivek Ragunathan wrote:
Are the members in a static class in C# class synchronized for multiple
thread access. If yes, are all static members in a C# class auto
synchronized ?
You can use the (System.Runtime.CompilerServices) MethodImpl attribute
to lock static or instance methods as MethodImplOptions.Synchronized.
<excerpt isbn="1590593863"> This may aid clarity a bit by cutting down
the nesting level within the method, but it's generally disparaged for
two rather good reasons:
1. The lock is obtained before entering the body of the method, and is
not released until the method returns. Using explicit locking gives
you finer-grained locking – you only keep the lock open as long as you
absolutely need to. While this isn't really an issue with simple
methods that add or remove an element from some sort of data
structure, these are also not usually the sort of complexly structured
methods where cutting one level of indenting can have any real effect
on clarity.
2. Synchronized methods are still using the Monitor mechanism, but
it's no longer obvious which object is being locked. (Static methods
lock the object's Type; instance methods lock this/Self, the object's
instance.) This can lead to locking failure or even deadlock. A hidden
lock can lead to lock failure if you 1) forget that synchronized
static methods do not lock the same data structure as synchronized
instance methods, if you 2) access the same static data structures
while explicitly locking something besides the class type, or if you
3) access the same data structures from the synchronized methods of a
different class. A hidden lock can lead to deadlock, both because you
are now locking a data structure that may be publicly visible, and
also because somebody maintaining your code may not be aware what a
synchronized method is actually locking.
</excerpt>
Answering you specifically: The members can be synchronized.
Synchronized static methods lock the class's runtime Type, and only
one synchronized static method (per class) may run at a time.
(Synchronized instance methods lock the class's runtime Type, and only
one synchronized instance method (per instance) may run at a time.
Locking is not automatic. You have to explicitly apply the attribute.
But then you do have very coarse-grained (all or none) sort-of unique
access to static or instance fields. Access is only sort-of unique,
because ... well ... locking this or typeof(this) can get you laughed
out of all the better offices.
--
<http://www.midnightbeach.com> Contracting, consulting, training
..NET 2.0 for Delphi Programmers <http://www.midnightbeach.com/.net>
In production - in stores by June