c# - MS Office Interop - 无法发布对 RCW 的引用

标签 c# .net com office-interop

我在我的应用程序中使用 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/

相关文章:

C# Enumerable.Take 带默认值

c# - 为什么Split函数有两个数组?

c# - 快速读取控制台输入

c# - ASP.net MVC - 每个 View 或每个操作一个 ViewModel?

c# - 在 VB6 中引用 .NET 程序集将不起作用

c# - 字符串到字符串的精度

c# - Swagger JSON 相对路径

.net - .NET 通用字典是否应该使用等于它将包含的项目数的容量初始化?

visual-studio - 如何从 Visual Studio C# 使用 Office?

c++ - Iwebbrowser2 导航 : No post-data submitted