glenn_r
asked on
vb.net singleton pattern block threads
I'm trying to implement the following singleton pattern in vb.net. In java i use the Synchronization directive to block theading invokation until the code block is cleared. In vb.net i've tried to use the synclock command but it requires an object referece first which kind of eliminates the benefit of the singleton pattern in the first place. What is vb.net equivalant to java's Synchronization keyword? Or is their some kind of other technique to achive this?
Public Class singleton
Shared uniqueinstance As singleton
Private Sub New()
End Sub
Public Shared Function getInstance() As singleton
SyncLock uniqueinstance
If uniqueinstance Is Nothing Then
uniqueinstance = New singleton
End If
End SyncLock
Return uniqueinstance
End Function
End Class
Public Class singleton
Shared uniqueinstance As singleton
Private Sub New()
End Sub
Public Shared Function getInstance() As singleton
SyncLock uniqueinstance
If uniqueinstance Is Nothing Then
uniqueinstance = New singleton
End If
End SyncLock
Return uniqueinstance
End Function
End Class
It seems OK as SyncLock has a similar functionality as it locks access to your protected code in a multithreaded application. Internally it uses the Monitor class as described here
ASKER
if you look at my pattern i'm trying to limit the class to a single instance
i can't use synclock as it requires a reference to the object and initially there is no object so i'm kids of deadlocked with synclock. is there some other way to block multiple threads from invoking my method?
i can't use synclock as it requires a reference to the object and initially there is no object so i'm kids of deadlocked with synclock. is there some other way to block multiple threads from invoking my method?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
ya your right i could just just eagar loading to solve the problem but if i want to use lazy loading where the instance only gets created when/if its used then i was considering creating a dummy object called blocker and then just set the synklock to that. Dones the same thing. thanks