How to run a method in a separate AppDomain?
In my scenario, I want to execute a method in a separate AppDomain. How many different ways could I take to achieve this?
Especially, I have the following question:
- Can I load an assembly into AppDomain A and execute its method in AppDomain B?
- It seems I achieve this with AppDomain.DoCallB开发者_JAVA百科ack Method and CrossAppDomainDelegate. I just cannot figure out how could it make sense to have the assembly and the method in different AppDomains. Is the same assmebly loaded again into the other AppDomain in order to execute the method?
In order to execute code in a separate AppDomain, the assembly containing that code has to be loaded into that AppDomain. From there you can call a method in the second AppDomain from your hosting domain using reflection or the "CreateInstance" methods on the AppDomain class.
Keep in mind, AppDomains are hard boundaries. In order to communicate across the AppDomain boundaries, you will need to use remoting or a true IPC-ish mechanism.
This is a bit dated, but I believe it still applies. http://blogs.msdn.com/b/suzcook/archive/2003/06/12/57169.aspx
Suzanne Cook had a series of posts related to this subject so it may be worth browsing her archives a bit.
Check out the "CreateInstance" family of methods on the AppDomain class. In the past I've used CreateInstanceFromAndUnwrap() quite a bit for this type of situation.
As far as your question about how many ways there are to do this... Um, many, but it depends a lot on the exact situation and what objects you have in hand.
Adding to Rob's correct answer, I want to mention that any attempt to call without using reflection is going to cause the assembly to be loaded into your calling AppDomain, which may well be what you're trying to avoid.
精彩评论