Is RaiseEvent thread safe?
In C# you write
if (event != null)
{
event.invoke();
}
and the C# code is not thread safe....
Is RaiseEvent thread safe?
In C# you write
if (event != null)
{
event.invoke();
}
and the C# code is not thread safe....
In C# you rather write:
EventHandler h= myEvent;
if (h!=null)
h(...);
This avoids the obvious problem (i.e. the unsubscribing between the test and the call), but this isn't thread-safe either.
Calling an event implies the listener is ready to process this event. This heavily depends on your specific situation, and is usually achieved through the use of synchronization mechanisms.
What exactly do you mean by "Thread safe" ?
If I need to do thread safe events, I write this:
Class Test
Public Event Click(ByVal sender As Object, ByVal e As EventArgs)
Public Event MouseIn(ByVal sender As Object, ByVal e As EventArgs)
Private Delegate Sub EventArgsDelegate(ByVal e As EventArgs)
Private ReadOnly _parent As Control
Public Sub New(ByVal parent As Control)
_parent = parent
End Sub
Private Sub OnClick(ByVal e As EventArgs)
If _parent.InvokeRequired Then
_parent.Invoke(New EventArgsDelegate(AddressOf OnClick), e)
Else
RaiseEvent Click(Me, e)
End If
End Sub
Private Sub OnMouseIn(ByVal e As EventArgs)
If _parent.InvokeRequired Then
_parent.Invoke(New EventArgsDelegate(AddressOf OnMouseIn), e)
Else
RaiseEvent MouseIn(Me, e)
End If
End Sub
End Class
Then whenever I need to raise the event I just use the OnClick(new eventargs(...))
, etc. If you use Reflector you can observe that most thread safe controls use a similar system.