Moving objects across AppDomains in .NET

与世无争的帅哥 提交于 2019-12-01 12:32:08

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.

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.

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.

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)

.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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!