如何清理 Excel.AppEvents AdviseSinks?
How to cleanup Excel.AppEvents AdviseSinks?
所以我 运行 在 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/
我不仅需要 IConnectionSink,还需要对作为参数传递的每个工作簿对象调用 Marshal.ReleaseComObject。
public class ExcelAppEventSink : Excel.AppEvents
{
... other functions ...
public void WorkbookOpen(Excel.Workbook Wb)
{
<-- operate on workbook -->
Marshal.ReleaseComObject(Wb);
}
... other functions ...
}
但是 2 年后微软 posted 的另一个博客 post 声称 Marshal.ReleaseComObject 是危险的。
https://blogs.msdn.microsoft.com/visualstudio/2010/03/01/marshal-releasecomobject-considered-dangerous/
因为我只需要释放 RCWs 在 2016 年打电话会不会更安全
CleanupUnusedObjectsInCurrentContext 在函数调用结束时改为?
额外阅读material:
所以这个答案真的很好: 不想为每个 COM 对象指定 using 但除此之外代码非常干净。
所以我 运行 在 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/
我不仅需要 IConnectionSink,还需要对作为参数传递的每个工作簿对象调用 Marshal.ReleaseComObject。
public class ExcelAppEventSink : Excel.AppEvents
{
... other functions ...
public void WorkbookOpen(Excel.Workbook Wb)
{
<-- operate on workbook -->
Marshal.ReleaseComObject(Wb);
}
... other functions ...
}
但是 2 年后微软 posted 的另一个博客 post 声称 Marshal.ReleaseComObject 是危险的。 https://blogs.msdn.microsoft.com/visualstudio/2010/03/01/marshal-releasecomobject-considered-dangerous/
因为我只需要释放 RCWs 在 2016 年打电话会不会更安全 CleanupUnusedObjectsInCurrentContext 在函数调用结束时改为?
额外阅读material:
所以这个答案真的很好: 不想为每个 COM 对象指定 using 但除此之外代码非常干净。