Ibrahim D. Ibrahim D. - 17 days ago 100
Vb.net Question

Is there a Singleton that raises events?

I have a singleton class, but I want its object to be able to raise events.
My current singleton code is as follows:

Private Shared ReadOnly _instance As New Lazy(Of WorkerAgent)(Function() New _
WorkerAgent(), LazyThreadSafetyMode.ExecutionAndPublication)

Private Sub New()
End Sub

Public Shared ReadOnly Property Instance() As WorkerAgent
Get
Return _instance.Value
End Get
End Property


Whenever I change
ReadOnly _instance As New..
into
ReadOnly WithEvents _instance As New...


I get an error saying
ReadOnly is not valid on a WithEvents deceleration


Although I can create the instance in the property itself, but I liked the above code because it is using .NET
Lazy
keyword which probably have great multithreading benefits.

Answer Source

This isn't an answer to your question as asked but it demonstrates why that question doesn't make sense. It also requires a fair chunk of code so posting in a comment wasn't really an option. This is how your singleton class would raise events, i.e. just like any other class, and how a consumer would handle those events, i.e. just like for any other type.

Singleton:

Public Class WorkerAgent

    Private Shared ReadOnly _instance As New Lazy(Of WorkerAgent)

    Private _text As String

    Public Shared ReadOnly Property Instance As WorkerAgent
        Get
            Return _instance.Value
        End Get
    End Property

    Public Property Text As String
        Get
            Return _text
        End Get
        Set
            If _text <> Value Then
                _text = Value
                OnTextChanged(EventArgs.Empty)
            End If
        End Set
    End Property

    Public Event TextChanged As EventHandler

    Private Sub New()
    End Sub

    Protected Overridable Sub OnTextChanged(e As EventArgs)
        RaiseEvent TextChanged(Me, e)
    End Sub

End Class

Note that the instance event is raised when the instance property changes, just as for any other type, singleton or not.

Consumer:

Public Class Form1

    Private WithEvents agent As WorkerAgent = WorkerAgent.Instance

    Private Sub agent_TextChanged(sender As Object, e As EventArgs) Handles agent.TextChanged
        '...
    End Sub

End Class

The field that the single instance is assigned to is where WithEvents gets used. As your error message states, that field cannot be declared ReadOnly too. If they want a ReadOnly field then they need to use AddHandler to handle events.