Tutorial :Moving objects across AppDomains in .NET



Question:

Is there a way to efficiently share or move .NET objects across AppDomains? I realize that the intent of AppDomains is to provide isolation - however I have a case where I need to move a relatively large, cached set of immutable objects that are expensive to compute and create. At the moment, I have a serialization approach that works, but is rather slow.


Solution:1

You cannot move an object across an AppDomain without serializing it. That is the main point of an AppDomain - you can almost think of it as a completely separate process.

This is where MarshallByRefObject comes into play. It allows you to use the object from the other AppDomain via Remoting, without having to serialize it across the AppDomain boundary. You're still working via remoting, so it will be slower than keeping the object in the same AppDomain, but if the object is large and you are using it infrequently, this can save a huge amount of time when compared with serializing it and unserializing it to make a new copy in the second AppDomain.


Solution:2

One thing you can try is to derive your objects from MarshalByRefObject. By default, objects are marshalled by value across AppDomains. For objects that derive from MarshalByRefObject, the caller is given a proxy to the object. All calls go through the proxy and are then marshalled to the object's app domain. This can reduce the need to create copies of all your objects in both app domains.


Solution:3

How about creating a separate application space for managing shared objects and then using either web services or remoting to get/set shared data? You would esentially be creating a central in-memory (depending on how you store the data) repository.


Solution:4

I believe that only a few 'blessed' objects are able to 'Marshal by bleed' i.e. just let drift across the boundaries (strings being one)

Remoting the calls should work if they are chunky rather than trying to copy the whole thing across (a big waste of memory if nothing else)


Solution:5

.NET Remoting is the best method I know of, although I have pretty limited experience. If you want to use this you need to read Advanced .NET Remoting, Second Edition by Ingo Rammer and Mario Szpuszta. When you start googling .NET Remoting Ingo's name pops up frequently. I found the book to be a little dated now, but quite valuable. I have not tried it with large binary serialized objects yet, but seems efficient with the smaller objects I have been working with. I did find you cannot have objects with SecureString properties, unless you want to implement custom serialization / deserialization for them.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »