"Value can not be null"单例实例化



我有一个单例类,我正在尝试实例化它,它给出了异常"Value cannot be null"

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

Dim devices As DeviceUnderTestBindingList

然后在我的表单中实例化。加载:

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#,但对它们的理解还不够。

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

Private Shared InstanceLock As Object

对此:

Private Shared InstanceLock As New Object()

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

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及以上版本)

最新更新