如何清理Excel.AppEvents AdviseLinks

本文关键字:AdviseLinks AppEvents Excel 何清理 | 更新日期: 2023-09-27 17:59:03

所以我在ole嵌入式场景中使用WorkbookOpen事件时遇到了一个问题:这是一个有充分记录的问题:

  • https://blogs.msdn.microsoft.com/mshneer/2008/10/18/com-interop-handling-events-has-side-effects/
  • https://blogs.msdn.microsoft.com/rcook/2008/10/30/iconnectionpoint-and-net-or-how-i-learned-to-stop-worrying-and-love-managed-event-sinks-part-1/

阅读此博客文章https://blogs.msdn.microsoft.com/vsofficedeveloper/2008/04/11/excel-ole-embedding-errors-if-you-have-managed-add-in-sinking-application-events-in-excel-2/

我不仅需要IConnectionSink,而且还需要对作为参数传递的每个工作簿对象调用Marshal.ReleaseComObject。

public class ExcelAppEventSink : Excel.AppEvents
{
... other functions ...
public void WorkbookOpen(Excel.Workbook Wb)
{
  <-- operate on workbook -->
  Marshal.ReleaseComObject(Wb);
}
... other functions ...
}

但两年后,微软发布的另一篇博客文章声称Marshal.ReleaseComObject是危险的。https://blogs.msdn.microsoft.com/visualstudio/2010/03/01/marshal-releasecomobject-considered-dangerous/

既然我只需要释放战俘,2016年打电话会更安全吗是否改为在函数调用结束时清除UnusedObjectsInCurrentContext?

额外阅读材料:

  • https://blogs.msdn.microsoft.com/vcblog/2006/09/19/mixing-deterministic-and-non-deterministic-cleanup/

如何清理Excel.AppEvents AdviseLinks

所以这个答案真的很好:https://stackoverflow.com/a/349202/不喜欢为每个COM对象指定using,但除此之外,代码非常干净。