VB.NET RaiseEvent, threadsafe?

耗尽温柔 提交于 2020-01-14 03:07:12

问题


Is RaiseEvent thread safe?

In C# you write

if (event != null)
{
    event.invoke();
}

and the C# code is not thread safe....


回答1:


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.




回答2:


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" ?



来源:https://stackoverflow.com/questions/2026355/vb-net-raiseevent-threadsafe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!