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

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", 111);
         string saa = tc.test();
         Console.WriteLine(saa);
    }
}
}

 

public static void Main(string[] args)
        {

            LogHelper.Log("Main start", "ffffffffff", 111);
            int i = 0;
            try
            {
                while (i < 11)
                {
                    i++;
                    myClass mc = new myClass();
                    mc.index = i;
                    LogHelper.Log("Main thread index:  【" + i + "", "ffffffffff", 111);
                    Thread t = new Thread(mc.Invoke);
                    t.Start();
                    Thread.Sleep(100);
                    Console.WriteLine(i);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            LogHelper.Log("Main end", "ffffffffff", 111);
            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. 输出结果



证明 StaticModel.IndexTest 是在各个domain中是独立的存在
posted @ 2016-12-27 18:19  YFeng_Lee  阅读(353)  评论(0编辑  收藏  举报