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. Ninputer

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

    Reply
  2. Eric

    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

    temp()

    End If

    End Sub

    End Class

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *