单例实例化时“值不能为空”

时间:2013-08-26 14:26:07

标签: vb.net exception singleton

我有一个单例类,我试图实例化它并给出异常"值不能为空"

我在我的主要表单中声明了一个引用,如:

Dim devices As DeviceUnderTestBindingList

然后在我的form.load中实例化:

devices = DeviceUnderTestBindingList.GetInstance

DeviceunderTestBindingList类如下:

Imports System.ComponentModel

Public Class DeviceUnderTestBindingList
    ' DeviceUnderTest is one of my other regular classes...
    Inherits System.ComponentModel.BindingList(Of DeviceUnderTest)

    Private Shared SingleInstance As DeviceUnderTestBindingList
    Private Shared InstanceLock As Object
    Private Shared ListLock As Object

    Private Sub New()
        MyBase.New()
    End Sub

    Public Shared ReadOnly Property GetInstance As DeviceUnderTestBindingList
        Get
            ' Ensures only one instance of this list is created.
            If SingleInstance Is Nothing Then
                SyncLock (InstanceLock)
                    If SingleInstance Is Nothing Then
                        SingleInstance = New DeviceUnderTestBindingList
                    End If
                End SyncLock
            End If
            Return SingleInstance
        End Get
    End Property
End Class

我之前使用过相同的模式没有任何问题,现在它突然引起异常,但为什么呢?

请注意:这是一个VB.NET Q!我已经阅读了很多处理类似问题的C#Q,但对它们的理解还不够。

2 个答案:

答案 0 :(得分:2)

问题是你不能{null}变量SyncLock。您只能在对象的有效实例上SyncLock。您需要更改此行:

Private Shared InstanceLock As Object

对此:

Private Shared InstanceLock As New Object()

答案 1 :(得分:0)

只是想补充一点,这个问题让我回过头来看看单例模式,我终于明白了如何使用Lazy(T)模式,虽然我仍然不确定它是如何线程安全的。这是VB代码:

Public Class MyClass
    Private Shared SingleInstance As Lazy(Of MyClass) = New Lazy(Of MyClass)(Function() New MyClass())

    Private sub New ()
        MyBase.New()
    End Sub

    Public Shared ReadOnly Property GetInstance
        Get
            Return SingleInstance.value
        End Get
    End Property
End Class

然后在我的OP中声明并实例化。 (这仅适用于.NET 4及更高版本)