| Imports System.Threading ''' <summary> ''' 一个线程隔离的 Singleton。 ''' </summary> Public Class ThreadwiseSingletonClass ThreadwiseSingleton(Of T As IDisposable) Private Shared _Factory As Func(Of T) ''' <summary> ''' 获取构建此实例的工厂类。 ''' </summary> Public Shared Property Factory()Property Factory() As Func(Of T) Get Return _Factory End Get Set(ByVal value As Func(Of T)) _Factory = value End Set End Property ''' <summary> ''' 获得线程中的唯一实例。 ''' </summary> Public Shared ReadOnly Property Instance()Property Instance() As T Get Dim threadSlot As LocalDataStoreSlot = Thread.GetNamedDataSlot(GetType(T).ToString) Dim threadSlotObj As Object = Thread.GetData(threadSlot) If threadSlotObj Is Nothing Then 'Create singleton instance Dim ins As T = Factory.Invoke Thread.SetData(threadSlot, ins) Return ins Else Return DirectCast(threadSlotObj, T) End If End Get End Property ''' <summary> ''' 私有的构造函数。 ''' </summary> Private Sub New()Sub New() End Sub ''' <summary> ''' 释放此 Singleton 实例使用的资源。请不要直接调用 Instance.Dispose()。 ''' </summary> Public Shared Sub Dispose()Sub Dispose() Instance.Dispose() '放空槽 Dim threadSlot As LocalDataStoreSlot = Thread.GetNamedDataSlot(GetType(T).ToString) Thread.SetData(threadSlot, Nothing) End Sub End Class |