Find references to the object in runtime

后端 未结 6 799
梦谈多话
梦谈多话 2020-12-15 18:02

I have an object, which lives forever. I am deleteing all references I can see, to it after using it, but it still not collected. Its life cycle is pretty sophisticated so I

6条回答
  •  庸人自扰
    2020-12-15 18:30

    I solved a similar issue with the SOS extension (which apparently does no longer work with Visual Studio 2013, but works fine with older versions of Visual Studio).

    I used following code to get the address of the object for which I wanted to track references:

    public static string GetAddress(object o)
    {
        if (o == null)
        {
            return "00000000";
        }
        else
        {
            unsafe
            {
                System.TypedReference tr = __makeref(o);
                System.IntPtr ptr = **(System.IntPtr**) (&tr);
                return ptr.ToString ("X");
            }
        }
    }
    

    and then, in Visual Studio 2012 immediate window, while running in the debugger, type:

    .load C:\Windows\Microsoft.NET\Framework\v4.0.30319\sos.dll
    

    which will load the SOS.dll extension.

    You can then use GetAddress(x) to get the hexadecimal address of the object (for instance 8AB0CD40), and then use:

    !do 8AB0CD40
    !GCRoot -all 8AB0CD40
    

    to dump the object and find all references to the object.

    Just keep in mind that if the GC runs, it might change the address of the object.

提交回复
热议问题