扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
作者:John Chen 来源:天极论坛整理 2007年10月14日
关键字: Visual Basic 线程安全 Singleton
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 |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。