.NET和COM - Class_Terminate /当对象超出范围时处置它

时间:2022-06-17 05:09:56

It is my understanding that for a VB6 COM object when it goes out of scope Class_Terminate is immediately called on the object to allow it to clean up.

我的理解是,对于VB6 COM对象,当它超出范围时,会立即调用Class_Terminate对象以允许它进行清理。

Is it possible to have that same functionality for a .NET object that is being called by COM?

是否可以为COM调用的.NET对象具有相同的功能?

The background to the question is based on the MSDN article: http://msdn.microsoft.com/en-us/library/aa479313.aspx

该问题的背景基于MSDN文章:http://msdn.microsoft.com/en-us/library/aa479313.aspx

This replaces the Session object in an ASP page with a custom object that serializes the Session information back to a database as soon as the page finishes by utilising Class_Terminate.

这将使用自定义对象替换ASP页面中的Session对象,该对象在页面完成后通过使用Class_Terminate将会话信息序列化回数据库。

I want to implement the object in .NET, however as the GC won't call the finalizer immediately it is a bit of a problem, as I don't want to have to wait for the object to be cleaned up before being serialized back into the database.

我想在.NET中实现该对象,但是因为GC不会立即调用终结器,所以它有点问题,因为我不想在序列化之前等待对象被清理进入数据库。

I could just implement IDisposiable and manually call Dispose() when finished with the Session, but that would require altering every existing ASP classic page rather than just being able to include a few lines in a standard include file.

我可以实现IDisposiable并在完成Session时手动调用Dispose(),但这需要更改每个现有的ASP经典页面,而不是只能在标准包含文件中包含几行。

So is there a way to automatically call the code to do the work that is required when the page has finished? :)

那么有没有办法自动调用代码来完成页面完成时所需的工作? :)

1 个解决方案

#1


Delegation. Wrap the .NET COM class in a VB6 Com Class that is a shell and in the Class_Terminate event of the wrapper call dispose.

代表团。将.NET COM类包装在一个shell的VB6 Com类中,并包装在包装器调用dispose的Class_Terminate事件中。

If you don't want to reimplement the entire interface in the VB6 COM Class then you could do something like

如果您不想重新实现VB6 COM类中的整个界面,那么您可以执行类似的操作

Public MyNETCOMObject as MyNETCOMObject

Private Class_Initialize()
  Set MyNETCOMObject = New MyNetCOMObject
End Sub

Private Class_Terminate()
  If Not MyNETCOMObject = Nothing then MyNETCOMObject.Dispose
  Set MyNETCOMObject = Nothing
End Sub

#1


Delegation. Wrap the .NET COM class in a VB6 Com Class that is a shell and in the Class_Terminate event of the wrapper call dispose.

代表团。将.NET COM类包装在一个shell的VB6 Com类中,并包装在包装器调用dispose的Class_Terminate事件中。

If you don't want to reimplement the entire interface in the VB6 COM Class then you could do something like

如果您不想重新实现VB6 COM类中的整个界面,那么您可以执行类似的操作

Public MyNETCOMObject as MyNETCOMObject

Private Class_Initialize()
  Set MyNETCOMObject = New MyNetCOMObject
End Sub

Private Class_Terminate()
  If Not MyNETCOMObject = Nothing then MyNETCOMObject.Dispose
  Set MyNETCOMObject = Nothing
End Sub