Monitor.Enter work across app domains?

N

not_a_commie

Suppose I pass an object to multiple app domains. I then use the lock
keyword or Monitor.Enter to lock on that object. Am I safe?

IIS puts several instances of my webservice each into their own app
domain. The provide an Application object that is used to share
objects across each of those instances. The Application object does
have its own Lock and Unlock methods. However, I don't want to block
the entire Application object.
 
J

Jeroen Mostert

not_a_commie said:
Suppose I pass an object to multiple app domains. I then use the lock
keyword or Monitor.Enter to lock on that object. Am I safe?
No, you're not. There's no such thing as a cross-domain lock.

To elaborate: either your object is serializable, in which case every
appdomain gets its own independent serialized copy of the object (so locking
only locks that particular object) or your object derives from
MarshalByRefObject, which creates proxies in remote appdomains. Locking
operations are not proxied -- if you lock on an MBRO, you're actually
locking the proxy. Synchronization across appdomains must be done by
shifting the responsibility for this to the remoting object.
IIS puts several instances of my webservice each into their own app
domain. The provide an Application object that is used to share
objects across each of those instances. The Application object does
have its own Lock and Unlock methods. However, I don't want to block
the entire Application object.

Are you sure this is how it works? As far as I'm aware, IIS creates only one
appdomain for each ASP.NET application. A single site can be accessed
through multiple paths, creating multiple applications, but these are
conceptually independent, and these do not share in-memory application
state. If an application has multiple sessions, then (barring extra worker
processes) these will still only execute in one appdomain. And if there
*are* extra worker processes, these do not share state. I'm not up to speed
with how IIS 7 does things, so my knowledge may be out of date.

The .Lock() and .Unlock() methods of the Application object only protect the
state object itself. Any objects you get or set are *themselves* not
synchronized (which is why you should generally treat them as immutable).
Also, getting or setting an item will implicitly lock and unlock, so these
methods are only provided as an optimization for when you do multiple
operations in sequence.

If your set of objects is fixed, you can bypass application state locking by
not using the Application object but by using your own static fields
(global.asax is a good place to declare them). You can then lock on the
objects stored in those fields individually.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top