Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

c# - Static Variable Instances and AppDomains, what is happening?

I have

public static class A
{
   public static string ConnString;
}

[Serializable]
public class Test{
   // Accesing A's field;
   public string ConnString{get{return A.ConnString;}set{A.ConnString=value;}}
}

void Main()
{
   A.ConnString = "InitialString"; // I set A.ConnString in the current domain

   var newDomain = AppDomain.CreateDomain("DomNew");
   Test TObj = newDomain.CreateInstanceAndUnwrap(typeof(Test).Assembly.FullName, typeof(Test).FullName) as Test ;

   TObj.ConnString = "NewDomainString"; // It is supposed to set A.ConnString in the newDomain aka a different instance of A.ConnString

   // Here it is supposed to print two different values
   Console.WriteLine(A.ConnString);  // "InitialString"
   Console.WriteLine(TObj.ConnString); // "NewDomainString"
}

But NO! The two WriteLines, print out the same value "NewDomainString"! WHY???

this code

TObj.ConnString = "NewDomainString"

is supposed to change the string in the newly created domain, but it seems they both refer to the same instance!

Why, what is happening here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...