使用 ActivationOption.Server 处理 ServicedComponent 中的共享成员

Disposal of Shared members in a ServicedComponent with ActivationOption.Server

出于多种原因,我需要在 .Net Framework 4 中创建一个 COM+ 组件。目的是在其自己的进程中托管该组件 (dllhost.exe),因此使用了 ActivationOption.Server。

我的组件代码需要在对象激活之间保留数据,这由工作线程维护。这个工作线程及其数据保存在我的基 class 的静态(共享)成员中。共享数据独立于调用者、其安全上下文、事务等。此外,工作线程对数据执行后台处理。

我需要清理数据并在处理dllhost进程时有序地终止工作线程。由于没有静态(共享)析构函数,我不知道该怎么做。在继承 ServicedComponent 的同时有什么我可以实现的吗?还有其他想法吗?谢谢。

这里有一些代码可以开始:

Imports System.EnterpriseServices

<Assembly: ApplicationName("MySender")> 
<Assembly: ApplicationActivation(ActivationOption.Server)> 

<ClassInterface(ClassInterfaceType.None), ProgId("MySender.Sender")> _
<Transaction(EnterpriseServices.TransactionOption.NotSupported)> _
Public Class Sender

    Inherits ServicedComponent
    Implements SomeLib.IMsgSender

    Shared worker As myWorker
    Shared sync As New Object

    Public Sub MyInstanceMethod(msg as string) Implements SomeLib.IMsgSender.SendMessage

        SyncLock sync
            If worker Is Nothing Then
                worker = New myWorker
                worker.StartThread()
            End If
        End SyncLock

        worker.Process(msg)

    End Sub

    'Something like this does not exist!'
    Shared Sub Dispose() 

        SyncLock sync
            If worker IsNot Nothing Then
                worker.StopThread()
            End If
        End SyncLock

    End Sub

End Class

AppDomain.ProcessExit 事件将在卸载域之前触发。如果 运行 的代码不会花太长时间,可以这样使用:

Imports System.EnterpriseServices

<Assembly: ApplicationName("MySender")> 
<Assembly: ApplicationActivation(ActivationOption.Server)>

<ClassInterface(ClassInterfaceType.None), ProgId("MySender.Sender")> _
<Transaction(EnterpriseServices.TransactionOption.NotSupported)> _
Public Class Sender

    Shared Sub New

        AddHandler AppDomain.CurrentDomain.ProcessExit, AddressOf MyDisposalCode

    End Sub

    '....

    Shared Sub MyDisposalCode(sender as Object, e as EventArgs)

        'My disposal code

    End Sub

End Class

请务必注意,.Net 将对此代码强制执行 2 秒超时。