Moving objects across AppDomains in .NET

家住魔仙堡 提交于 2019-12-19 10:48:27

问题


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.


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




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




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




回答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)




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



来源:https://stackoverflow.com/questions/981773/moving-objects-across-appdomains-in-net

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