我的理解是,无论何时使用.net互操作COM对象,都必须调用Marshal.ReleaseComObject,它将引用计数减少1,以确保在引用计数命中后释放Com对象使用的内存0
尽管如此,请考虑以下示例代码,该代码取自VS加载项项目:
public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
{
DTE2 _dte = (DTE2)application;
Events e = _dte.Events;
for (int x = 0; x < 100; x++)
{
e = _dte.Events;
}
Console.WriteLine(Marshal.ReleaseComObject(e));//100
但如果我这样做,
public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
{
DTE2 _dte = (DTE2)application;
CommandBar commandBar = ((CommandBars)_dte.CommandBars)["MenuBar"];
CommandBarControls ctrls = commandBar.Controls;
for (int x = 0; x < 100; x++)
{
ctrls = commandBar.Controls;
}
Console.WriteLine(Marshal.ReleaseComObject(ctrls));//0
}
因此,在这两种情况下,代码都会调用一个多次返回“Com Object”的属性,但看起来引用计数并没有增加,正如我在第二个例子中所预期的那样。
有人可以解释上述行为吗?