Events and race conditions

JayBaz points out something that is worth keeping in mind about events: they can be subject to race conditions in multi-threaded scenarios. In VS 2002 and VS 2003, you’ll need to do what the C# folks do and handle the race condition yourself:

Event Moved(ByVal x As Integer, ByVal y As Integer)

Sub Move(ByVal x As Integer, ByVal y As Integer)
Dim temp As MovedEventHandler = Me.MovedEvent

If Not temp Is Nothing Then
temp(x, y)
End If
End Sub

(The names “xEventHandler” and “xEvent” are automagically generated names – the first is the delegate type of the event and the second is the hidden field generated to hold the event delegate.)

In Whidbey, however, we’ve changed the code generation for RaiseEvent so that this will be done automatically for you. We work hard so you don’t have to!

3 thoughts on “Events and race conditions”

  1. Is there any way to implement as the follow C# codes in Visual Basic 2005?
    public event EventHandler MyEvent
    _MyEvent += value;
    _MyEvent -= value;
    I think it is an important feature.

  2. Just a note on something that caused me some confusion: if the event implements an event on an interface, the event handler is defined on the interface as well, not on the implementing class:

    Public Interface IFoo

    Event DidFoo()

    End Interface

    Public Class Foo

    Implements IFoo

    Event DidFoo Implements IFoo.DidFoo

    Public Sub DoFoo()

    Dim temp As IFoo.DidFooEventHandler = Me.DidFooEvent

    If Not temp Is Nothing Then


    End If

    End Sub

    End Class

Leave a Reply