DoCallBack CrossAppDomainDelegate behavior for non-static delegates

Please consider the following code snippet:

// Create a new application domain AppDomain ad = AppDomain.CreateDomain("New domain"); Worker work = new Worker(); // if Worker class is marked as 'MarshalByRefObject', this will run in current // appdomain. // if Worker class is NOT marked as 'MarshalByRefObject' and is marked as // 'Serializable', this will run in a new appdomain. ad.DoCallBack(work.PrintDomain); // or ad.DoCallBack(new CrossAppDomainDelegate(work.PrintDomain)); // But for static methods: // If ppp method is static, no marking is required and it will run in // a new AppDomain. ad.DoCallBack(Worker.ppp); 

How do we explain this behavior of DoCallBack ?

  • Why is the non-static PrintDomain method executed in the current domain when the Worker class is marked with MarshalByRefObject ?
  • Why is the non-static PrintDomain method executed in the new AppDomain when the Worker class is marked Serializable ?
  • Why doesn't the static method need marking?
+6
source share
1 answer

Why is the non-static PrintDomain method executed in the current domain when the Worker class is marked with MarshalByRefObject?

Thanks to what MBRO does, it creates a proxy server for the object created in your main application. Which marshals the call from the secondary appdomain to the appdomain to which the object belongs, the primary appdomain.

Why is the non-static PrintDomain method executed in the new AppDomain when the Worker class is marked Serializable?

Because this script does not use proxies. The object itself is marshaled from primary to secondary appdomain. Perhaps because you marked it [Serializable]. Therefore, the call is made in the secondary application domain.

Why doesn't the static method need marking?

It is not clear what you mean by "marking", but for a static method this is no different. Some code to reproduce, remove the comment on the base class to compare two scenarios:

 using System; class Program { static void Main(string[] args) { var dom = AppDomain.CreateDomain("Test"); var obj = new WorkerMbro(); dom.DoCallBack(obj.PrintDomain); dom.DoCallBack(obj.PrintDomainStatic); Console.ReadLine(); } } [Serializable] class WorkerMbro /* : MarshalByRefObject */ { public void PrintDomain() { Console.WriteLine(AppDomain.CurrentDomain.FriendlyName); } public void PrintDomainStatic() { Console.WriteLine(AppDomain.CurrentDomain.FriendlyName); } } 

It is displayed as sent:

 Test Test 

The output is with deleted comments, so a proxy server is used:

 ConsoleApplication1.vshost.exe ConsoleApplication1.vshost.exe 
+6
source

Source: https://habr.com/ru/post/945136/


All Articles