static lock

  • Thread starter Thread starter memememe
  • Start date Start date
M

memememe

in java if I was calling a synchronized block and wanted to sync it even for
static blocks of code I could do a synchronize(theObject.getClass()), can I
do a lock(theObject.GetType()) on C# and will it lock for static blocks of
code that use that object type?
 
memememe said:
in java if I was calling a synchronized block and wanted to sync it even for
static blocks of code I could do a synchronize(theObject.getClass()), can I
do a lock(theObject.GetType()) on C# and will it lock for static blocks of
code that use that object type?

Note that even if you've just found the answer, I'd suggest *not*
locking on the type in either Java or C# - it could cause problems if
other classes also lock on the type.

Instead, have a private member which you lock on. So, for a static
lock:

private static Object padlock = new Object();

....

lock (padlock)
or
synchronized (padlock)


(Note that the "private" modifier is unnecessary in C#.)

I'd suggest doing the same for instance locks as well. That way you
know nothing else is going to be locking on the same reference, as
nothing *has* the same reference. It also means you can use finer-
grained locks simply.
 
I'd suggest doing the same for instance locks as well. That way you
know nothing else is going to be locking on the same reference, as
nothing *has* the same reference. It also means you can use finer-

As a note, if you will be supplying a "SyncRoot" property (e.g using
ICollection, IList, etc.) for your object, then it probably does not matter
if you use "this" or another internal object as any class that can gain
access to your object ref could also get access to SyncRoot and lock either
or both. So the net effect would be the same if using one lock. You will
notice most (if not all) of the Framework classes that derive from
ICollection and return a SyncRoot (i.e. Array, Queue, Stack, ArrayList,
HashTable, etc.) just return "this" as the sync object probably for this
reason. If you don't need or want to expose a sync object, then I agree a
private object is probably better.
 
Back
Top