简体   繁体   English

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

[英]MS Office Interop - can't release references to RCW

I'm using Microsoft.Office.Interop.PowerPoint in my app to control presentation SlideShow. 我在应用程序中使用Microsoft.Office.Interop.PowerPoint来控制演示幻灯片。 I can connect to PowerPoint using code 我可以使用代码连接到PowerPoint

PowerPointApp = Marshal.GetActiveObject("PowerPoint.Application") as Microsoft.Office.Interop.PowerPoint.Application;

and all works ok, but I can't release refereces (after SlideShow ends and PowerPoint was CLOSED) using 一切正常,但我无法使用以下方式释放裁判(在SlideShow结束且PowerPoint关闭后)

 Marshal.FinalReleaseComObject(PowerPointApp);

This call still throws an exception: 此调用仍然引发异常:

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)).

I tried to wrap both methods (GetActiveObject and FinalReleaseComObject) into: 我试图将两种方法(GetActiveObject和FinalReleaseComObject)包装为:

 App.Current.Dispatcher.Invoke((MethodInvoker)delegate{ ... });`

to ensure that both methods are called from same thread, but I got same exception. 确保从同一线程调用这两种方法,但是我遇到了相同的异常。

I also tried to release references when PowerPoint is still runnig - in this case, references to RCW are released without exception (but I need to release these referencers after PowerPoint is closed) 我还尝试在PowerPoint仍运行时释放引用-在这种情况下,对RCW的引用无一例外地被释放(但我需要在PowerPoint关闭后释放这些引用)

Use the ReleaseComObject instead of the FinalReleaseComObject method. 使用ReleaseComObject而不是FinalReleaseComObject方法。 The Systematically Releasing Objects article states the following: 系统发布对象文章指出以下内容:

Use System.Runtime.InteropServices.Marshal.ReleaseComObject to release an Office/PowerPoint object when you have finished using it. 使用完System.Runtime.InteropServices.Marshal.ReleaseComObject即可释放Office / PowerPoint对象。 Then set a variable to Nothing in Visual Basic (null in C#) to release the reference to the object. 然后在Visual Basic中将变量设置为Nothing(在C#中为null)以释放对该对象的引用。

It is related to Outlook, but the same principles can be applied to any Office application. 它与Outlook有关,但是相同的原理可以应用于任何Office应用程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM