AppDomain对于静态对象的独享引用

时间:2022-03-16 07:46:58

AppDomain可以理解为一个独立的沙箱,当有独立的第静态对象在appDomain中被访问时,会在appDomain中产生独立的内存对象。比如appDomain1 appDomain2同时对 静态对象A有引用时,appDomain1.A与appDomain2.A是两个对象。

1.

静态对象属性

public class StaticModel
{
public static int IndexTest;
}

2.

public class myClass
{
public int index;
public void Invoke()
{
using (TestProctectedCodeInvoke tc = new TestProctectedCodeInvoke())
{
LogHelper.Log("index:" + index + "----------Invoke thread .id:" + Thread.CurrentThread.ManagedThreadId, "ddd", );
string saa = tc.test();
Console.WriteLine(saa);
}
}
}
public static void Main(string[] args)
{ LogHelper.Log("Main start", "ffffffffff", );
int i = ;
try
{
while (i < )
{
i++;
myClass mc = new myClass();
mc.index = i;
LogHelper.Log("Main thread index: 【" + i + "】", "ffffffffff", );
Thread t = new Thread(mc.Invoke);
t.Start();
Thread.Sleep();
Console.WriteLine(i);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
LogHelper.Log("Main end", "ffffffffff", );
Console.ReadLine();
}
class TestProctectedCodeInvoke: IDisposable
{
public string test()
{
string dllpath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory + "ClassLibrary1.dll");
AssemblyDomain ad = new AssemblyDomain();
object s = ad.Invoke(dllpath, "ClassLibrary1.Class1", "GetName");
return s.ToString();
} public void Dispose()
{
Console.WriteLine("Dispose");
}
~TestProctectedCodeInvoke()
{
Console.WriteLine("TestProctectedCodeInvoke .xigou");
}
}

3. 输出结果

AppDomain对于静态对象的独享引用

证明 StaticModel.IndexTest 是在各个domain中是独立的存在