在 C# 中使用 COM IDispatch::GetTypeInfo() 时发生内存泄漏

发布于 2024-09-28 08:40:15 字数 675 浏览 0 评论 0原文

我在 COM dll(C#、.NET Framework v2)中有以下函数:

public void Leak(object jsObject) {
    Type comType;
    IDispatch disp = (IDispatch)jsObject;
    disp.GetTypeInfo(0, 0, out comType); // this line causes the leak
    Marshal.FinalReleaseComObject(disp);
    Marshal.FinalReleaseComObject(jsObject);
    disp = null;
    jsObject = null;
    GC.Collect(); GC.WaitForPendingFinalizers();
}

当从 JScript 重复调用此函数时,它会泄漏大量内存:

var util = new ActiveXObject('MyLeakyCOM.MyLeakyCOM');

for(var i = 0; i < 1000; i++) {
    util.Leak({});
}

我已经尝试使用 while(Marshal. ReleaseComObject(disp) > 0) {} 但也没有运气。

I have the following function in a COM dll (C#, .NET framework v2):

public void Leak(object jsObject) {
    Type comType;
    IDispatch disp = (IDispatch)jsObject;
    disp.GetTypeInfo(0, 0, out comType); // this line causes the leak
    Marshal.FinalReleaseComObject(disp);
    Marshal.FinalReleaseComObject(jsObject);
    disp = null;
    jsObject = null;
    GC.Collect(); GC.WaitForPendingFinalizers();
}

When calling this function repeatedly from a JScript, it leaks lots of memory:

var util = new ActiveXObject('MyLeakyCOM.MyLeakyCOM');

for(var i = 0; i < 1000; i++) {
    util.Leak({});
}

I've already tried to release the object with while(Marshal.ReleaseComObject(disp) > 0) {} but also no luck.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绮筵 2024-10-05 08:40:15

我是一个 C++ 人员而不是 C# 人员,但我突然意识到您还应该发布 comType

Marshal.FinalReleaseComObject(comType);

ITypeInfo 对象是一个正确的 COM 对象,它是 >AddRef 将由 GetTypeInfo 的实现调用。

I'm a C++ guy rather than a C# guy, but it strikes me that you should also be releasing comType:

Marshal.FinalReleaseComObject(comType);

The ITypeInfo object is a proper COM object and it's AddRef will have been called by the implementation of GetTypeInfo.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文