Static Variable Instances and AppDomains, what is happening?

前端 未结 2 1965
面向向阳花
面向向阳花 2020-12-05 10:49

I have

public static class A
{
   public static string ConnString;
}

[Serializable]
public class Test{
   // Accesing A\'s field;
   public string ConnStrin         


        
相关标签:
2条回答
  • 2020-12-05 11:08

    There are only two ways for a class to be accessible from another AppDomain- one is is the class is [Serializable], as your Test class is, the other is if the class inherits from MarshalByRefObject. Because your class is Serializable, a copy of it is created for every cross-AppDomain call. So the Test that the main appdomain gets when you call...

    Test TObj = newDomain.CreateInstanceAndUnwrap(typeof(Test).Assembly.FullName, typeof(Test).FullName) as Test;
    

    is actually not the Test instance that was created in the "DomNew" AppDomain- it is a copy local to the "main" AppDomain, and therefore references the static variables from the "main" AppDomain.

    If you want Test to exhibit the behavior that you expect, make it inherit from MarshalByRefObject instead of being Serializable.

    0 讨论(0)
  • 2020-12-05 11:10

    You marked your Test class as Serializable. This is wrong. You should have derived from MarshalByRef. Otherwise TObj will just be a local copy in the current AppDomain.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题