前十几天和装配脑袋聊天的时候,他把 ThreadwiseSingleton 发给了我,我随后改写成泛型类。事实上,它基于 Threadslot 构建,因此达到了线程隔离的效果。您需要传入一个 Func(Of TResult) 完成初始化的工作。如果您的类中含有非托管资源,并无法预见可能的错误时,请使用一个 Try...Finally... 包裹将要运行的程序。同时感到抱歉的是,拖延了很久很久才发出来。
Imports System.Threading
''' <summary>
''' 一个线程隔离的 Singleton。
''' </summary>
Public Class ThreadwiseSingleton(Of T As IDisposable)
Private Shared _Factory As Func(Of T)
''' <summary>
''' 获取构建此实例的工厂类。
''' </summary>
Public Shared 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() 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()
End Sub
''' <summary>
''' 释放此 Singleton 实例使用的资源。请不要直接调用 Instance.Dispose()。
''' </summary>
Public Shared Sub Dispose()
Instance.Dispose()
'放空槽
Dim threadSlot As LocalDataStoreSlot = Thread.GetNamedDataSlot(GetType(T).ToString)
Thread.SetData(threadSlot, Nothing)
End Sub
End Class
''' <summary>
''' 一个线程隔离的 Singleton。
''' </summary>
Public Class ThreadwiseSingleton(Of T As IDisposable)
Private Shared _Factory As Func(Of T)
''' <summary>
''' 获取构建此实例的工厂类。
''' </summary>
Public Shared 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() 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()
End Sub
''' <summary>
''' 释放此 Singleton 实例使用的资源。请不要直接调用 Instance.Dispose()。
''' </summary>
Public Shared Sub Dispose()
Instance.Dispose()
'放空槽
Dim threadSlot As LocalDataStoreSlot = Thread.GetNamedDataSlot(GetType(T).ToString)
Thread.SetData(threadSlot, Nothing)
End Sub
End Class