In general, the singleton model should be quite common in the design model. It can save valuable CPU or memory resources and avoid unnecessary object creation overhead. However, in multi-threaded applications, traditional Singleton may cause instability for non-thread-safe database components. If synclock is used for synchronization, the performance loss may be greater, especially in Asp.net applications with high concurrent access.
He sent threadwisesingleton to me when chatting with the Assembly head in the last few days. Then I changed it to a generic class. In fact, it is built based on threadslot, thus achieving thread isolation. You need to input a func (of tresult) to complete initialization. If your class contains unmanaged resources and you cannot predict possible errors, use a try... finally... package to run Program . At the same time, I am sorry that it took a long time to get out.
Imports System. threading
' ''<Summary>
' '''Singleton of thread isolation.
' ''</Summary>
Public Class Threadwisesingleton (of T As Idisposable)
Private Shared _ Factory As Func (of T)
' ''<Summary>
' ''Gets the factory class for building this instance.
' ''</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>
' ''To obtain the unique instance in the thread.
' ''</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>
' ''Private constructor.
' ''</Summary>
Private Sub New()
End sub
' ''<Summary>
' ''To release the resources used by this Singleton instance. Do not directly call instance. Dispose ().
' ''</Summary>
Public Shared Sub Dispose ()
Instance. Dispose ()
' Empty slot
Dim Threadslot As Localdatastoreslot = Thread. getnameddataslot ( GetType (T). tostring)
Thread. setdata (threadslot, Nothing )
End sub
End Class