单例初始化多次



我以前没有使用过单例,所以也许我的想法完全错误,但我认为关键是它只能初始化一次,任何调用它的人都会引用同一个实例..?

所以我从一个例子中得到了这个。GetInstance() 是从我的程序中的数百个不同位置调用的,当我调试时,"Prog = New Program"行不断被击中。我认为这正是不应该发生的事情。还是我有一些根本性的误解?

    ' ********************** THREAD SAFE SINGLETON **************************
 Public Class Program 
    Private Shared Prog As Program = Nothing
    Private Shared ReadOnly singletonLock As New Object()
    Public Shared Function GetInstance() As Program
        SyncLock singletonLock
            If Prog Is Nothing Then
                Prog = New Program
            End If
            Return Prog
        End SyncLock
    End Function

编辑:

似乎"New"子在第一个完成之前触发了对Program.GetInstance的多次调用。这是因为我之前在此类中有很多共享的公共对象,自从该类成为单例以来,这些对象不再共享。这些对象在初始化时会调用 Program 类以引用它的其他对象。

猜猜答案是这样的:

似乎"New"子在第一个完成之前触发了对Program.GetInstance的多次调用。这是因为我之前在此类中有很多共享的公共对象,自从该类成为单例以来,这些对象不再共享。这些对象在初始化时会调用 Program 类以引用它的其他对象。 所以;循环引用。

这是从 c# 中抄写的,但可能会工作得更好一些(不过,发布代码应该可以工作。

Public NotInheritable Class Singleton
    Private Shared ReadOnly Singleton instance = new Singleton();
    ' Explicit static constructor to tell compiler
    ' not to mark type as beforefieldinit
    Shared Sub New()
    End Sub
    Private Sub New()
    End Sub
    Public Shared ReadOnly Property Instance As Singleton
        Get
            return Me.instance;
        End Get
    End Property
End Class

应该在没有任何锁定的情况下很好地工作,但正如 Skeet 所说,可能会更懒惰。

最新更新