我在我的应用程序中使用 Microsoft.Office.Interop.PowerPoint 来控制演示幻灯片。我可以使用代码连接到 PowerPoint
PowerPointApp = Marshal.GetActiveObject("PowerPoint.Application") as Microsoft.Office.Interop.PowerPoint.Application;
一切正常,但我无法使用
发布引用(在幻灯片放映结束和 PowerPoint 关闭后) Marshal.FinalReleaseComObject(PowerPointApp);
这个调用仍然抛出异常:
A first chance exception of type 'System.InvalidCastException' occurred in mscorlib.dll
Additional information: Unable to cast COM object of type 'System.__ComObject' to interface type 'System.Runtime.InteropServices.ComTypes.IConnectionPoint'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{B196B286-BAB4-101A-B69C-00AA00341D07}' failed due to the following error: The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD)).
我尝试将两种方法(GetActiveObject 和 FinalReleaseComObject)包装到:
App.Current.Dispatcher.Invoke((MethodInvoker)delegate{ ... });`
确保从同一个线程调用这两个方法,但我得到了相同的异常。
我还尝试在 PowerPoint 仍在运行时释放引用 - 在这种情况下,对 RCW 的引用无一异常(exception)地被释放(但我需要在 PowerPoint 关闭后释放这些引用)
最佳答案
使用 ReleaseComObject 而不是 FinalReleaseComObject 方法。 Systematically Releasing Objects文章陈述如下:
Use System.Runtime.InteropServices.Marshal.ReleaseComObject to release an Office/PowerPoint object when you have finished using it. Then set a variable to Nothing in Visual Basic (null in C#) to release the reference to the object.
它与 Outlook 相关,但同样的原则可以应用于任何 Office 应用程序。
关于c# - MS Office Interop - 无法发布对 RCW 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28187753/