COM Interop-"COM对象已经从其基础RCW中分离出来,无法使用".和内存泄漏. [英] COM Interop - "COM object has been separated from its underlying RCW cannot be used" and memory leaks.
问题描述
您好,我正在尝试在要构建的应用程序中使用旧版COM对象.我通读了以下文章,并按照建议的方式实现了处置设计模式.
http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx
http://msdn.microsoft.com/zh-cn/library/system.idisposable.dispose.aspx
这是我面临的问题:
- 如果我打电话给dispose然后打电话给 元帅 . 在不调用 GC 的情况下释放ComObject() . 收集 ();和 GC . WaitForPendingFinalizers (),我的应用程序将泄漏.
- 如果我不明确调用dispose,而我的析构函数调用dispose(如设计模式所建议的那样),则会出现异常"COM对象已与其底层RCW分离,无法使用."
- 如果我不调用析构函数中的dispose,则我的应用程序会泄漏.
- If I call dispose and then call Marshal.ReleaseComObject() without calling GC.Collect(); and GC.WaitForPendingFinalizers(), my app will leak.
- If I don't explictily call dispose and my destructor calls dispose (like the design pattern suggests), I get an exception "COM object has been separated from its underlying RCW cannot be used."
- If I don't call dispose in the destructor, my app leaks.
Hi
I'm trying to use a legacy COM object in an application that I'm building. I've read through the following articles and I have implemented the dispose design pattern as suggested.
http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx
http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx
http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx
Here are the issues I face:
所以我有点困惑.到底该如何释放我的COM对象而不泄漏或崩溃我的应用程序???其他所有人都在做什么以释放其COM对象?
So I'm kinda stumped. How on earth to do I release my COM object without leaking or crashing my app??? What is everyone else doing to release their COM object?
谢谢
推荐答案
发布您的代码. COM的一般规则:
1.引用中不要使用多个点,因此以下内容不好:
范围范围= excel.Worksheets [0] .UsedRange; //太多点.
相反,请使用以下代码:
工作表wks = excel.Worksheets;
工作表ws =(工作表)wks [0];
范围范围=(Range)ws.UsedRange ;
这样,您将对每个COM对象只有一个引用.
2.确保从获取它们的相反顺序调用ReleaseComObject.因此,对于上面的示例,您将释放范围,然后释放ws,然后释放wks.不要反过来释放它们.
如果这有道理,请尝试应用它.如果没有,请发布您的代码.请查看以下链接以获取更多信息:
Post your code. General rules for COM:
1. Don't use more than one dot in your references, thus the following is not good:
Range range = excel.Worksheets[0].UsedRange; // too many dots.
instead, use this:
Worksheets wks = excel.Worksheets;
Worksheet ws = (Worksheet)wks[0];
Range range = (Range)ws.UsedRange;
In this way, you'll have a single reference for each COM object.
2. Make sure you call ReleaseComObject in a reverse order from where you acquired them. So for the example above, you would release range, then ws, then wks. Don't release them the other way around.
If this makes sense, try applying it. If not, post your code. Check out the following link for more info:
Excel Not closing after starting C# [.NET] Thread
这篇关于COM Interop-"COM对象已经从其基础RCW中分离出来,无法使用".和内存泄漏.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!