我有一个小测试程序.当我查看主线程的堆栈对象时,它在那里显示两次MyClass.任何想法为什么堆栈上有两个MyClass对象?
class Program
{
struct MyStruct
{
int x;
int y;
}
class MyClass
{
int x;
int y;
}
static void Main(string[] args)
{
MyStruct s ;
MyClass c = new MyClass();
}
}
0:000> !DumpStackObjects
OS Thread Id: 0xf74 (0)
RSP/REG Object Name
000000000023e9e8 00000000028f3c90 ConsoleApplication2.Program+MyClass
000000000023e9f8 00000000028f3c90 ConsoleApplication2.Program+MyClass
000000000023ea10 00000000028f3c70 System.Object[] (System.String[])
000000000023eb98 00000000028f3c70 System.Object[] (System.String[])
000000000023ed80 00000000028f3c70 System.Object[] (System.String[])
000000000023eda8 00000000028f3c70 System.Object[] (System.String[])
最佳答案:
实际上它显示了唯一的实例被引用了两次.请注意,最左侧列中的值不同.它可以是不同的寄存器或堆栈帧的不同部分,它们指向同一个实例.
根据我的经验,这种情况经常发生(特别是对于调试版本). !dso对于定位对象很有用,在这种情况下,重要的列是Object列,它保存实际的引用.
例如.如果我从调试器运行上面的示例并在Main上放置一个断点,则dso的输出在Main方法返回之前就像这样.
0:000> !dso
OS Thread Id: 0x1944 (0)
ESP/REG Object Name
eax 0240b2e0 TestApp.Program+MyClass
ecx 0240b2e0 TestApp.Program+MyClass
0014F224 0240b2d0 System.Object[] (System.String[])
0014F3CC 0240b2d0 System.Object[] (System.String[])
0014F400 0240b2d0 System.Object[] (System.String[])
正如您所看到的那样,尽管C#源只有一个引用,但eax和ecx寄存器都包含对实例的引用.
如果你看看Main的JIT编译代码,它看起来像这样
0:000> !u 00200070
Normal JIT generated code
TestApp.Program.Main(System.String[])
Begin 00200070, size 46
C:\dev2010\TestApp\TestApp\Program.cs @ 33:
>>> 00200070 55 push ebp
00200071 8bec mov ebp,esp
00200073 83ec14 sub esp,14h
00200076 33c0 xor eax,eax
00200078 8945f4 mov dword ptr [ebp-0Ch],eax
0020007b 8945f8 mov dword ptr [ebp-8],eax
0020007e 894dfc mov dword ptr [ebp-4],ecx
00200081 833d3c31150000 cmp dword ptr ds:[15313Ch],0
00200088 7405 je 0020008f
0020008a e8c05ac268 call clr!JIT_DbgIsJustMyCode (68e25b4f)
0020008f 33d2 xor edx,edx
00200091 8955f0 mov dword ptr [ebp-10h],edx
00200094 90 nop
C:\dev2010\TestApp\TestApp\Program.cs @ 35:
00200095 b960391500 mov ecx,153960h (MT: TestApp.Program+MyClass)
0020009a e8811ff4ff call 00142020 (JitHelp: CORINFO_HELP_NEWSFAST)
0020009f 8945ec mov dword ptr [ebp-14h],eax
002000a2 8b4dec mov ecx,dword ptr [ebp-14h]
002000a5 ff158c391500 call dword ptr ds:[15398Ch] (TestApp.Program+MyClass..ctor(), mdToken: 0:000> !dso
OS Thread Id: 0x1944 (0)
ESP/REG Object Name
eax 0240b2e0 TestApp.Program+MyClass
ecx 0240b2e0 TestApp.Program+MyClass
0014F224 0240b2d0 System.Object[] (System.String[])
0014F3CC 0240b2d0 System.Object[] (System.String[])
0014F400 0240b2d0 System.Object[] (System.String[])
003)
002000ab 8b45ec mov eax,dword ptr [ebp-14h]
002000ae 8945f0 mov dword ptr [ebp-10h],eax
C:\dev2010\TestApp\TestApp\Program.cs @ 36:
002000b1 90 nop
002000b2 8be5 mov esp,ebp
002000b4 5d pop ebp
002000b5 c3 ret