《Advanced .NET Debugging》 读书笔记 Listing 5-3: Object的Roots的示例

源代码如下:

using System;
using System.Text;
using System.Threading;

namespace Advanced.NET.Debugging.Chapter5
{
    class Name
    {
        private string first;
        private string last;

        public string First { get { return first; } }
        public string Last { get { return last; } }

        public Name(string f, string l)
        {
            first = f; last = l;
        }
    }

    class Roots
    {
        public static Name CompleteName = new Name ("First", "Last");

        private Thread thread;
        private bool shouldExit;

        static void Main(string[] args)
        {
            Roots r = new Roots();
            r.Run();
        }

        public void Run()
        {
            shouldExit = false;

            Name n1 = CompleteName;

            thread = new Thread(this.Worker);
            thread.Start(n1);

            Thread.Sleep(1000);

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();

            shouldExit = true;

        }

        public void Worker(Object o)
        {
            Name n1 = (Name)o;
            Console.WriteLine("Thread started {0}, {1}",
                              n1.First,
                              n1.Last);

            while (true)
            {
                // Do work
                Thread.Sleep(500);
                if (shouldExit)
                    break;
            }
        }
    }
}

可见程序中三处存在对同一对象的引用。下面通过WinDbg进行验证:

1. 在WinDbg里载入05Roots.exe

2. 在断点处,执行 !loadby sos.dll mscorwks

3. 执行 ~0s 切换线程

4. 执行 !clrstack –a 可得到heap对象的位置:

image

5. !gcroot 0x0000000002613870, 查找

image

 以第一条为例(RSP:22ee58:Root:0000000002613870(Advanced.NET.Debugging.Chapter5.Roots),意思是在RSP的22ee58处,产生了对0000000002613870的Root引用。

posted on 2011-01-04 22:46  李志鹏  阅读(210)  评论(0)    收藏  举报

导航