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 _
Private Sub New()
Public Shared ReadOnly Property Instance() As WorkerAgent
ReadOnly _instance As New..
ReadOnly WithEvents _instance As New...
ReadOnly is not valid on a WithEvents deceleration
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.
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.
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.