views:

20

answers:

2

I have read where an event is triggered on another thread from the one that created the controls on a Windows Form.

Therefore, the event handler can't directly update the controls (like changing a button's color).

I read the explainations about Invoke or BeginInvoke being needed.

My question: Why can't an event handler just be passed 'this' as an agrument.

'this' being the form whose controls have buttons that want THEIR COLORS CHANGED !! ;)

I can swear I've seen instances where a delegate can take a 'this' - but maybe not...

+1  A: 

There's nothing stopping an event handler on another thread just going in and screwing around with the internal state of the button.

However, it causes bad things to happen - as an example, what would happen if you changed a property of a control while something else was also trying to write to it?

Only one thread should be screwing around with the internal state of an object at a time - if you call methods directly on that object from another thread, you can't guarantee that something else isn't doing the same.

Invoke gets around this by not calling it directly - instead it says to the thread that 'owns' the object "Hey, could you call this method on that object when you've got a moment?", thus ensuring that the method is only called when the object is in a consistent state.

Anon.
Excellent -thanks!
Joe
+1  A: 

If you are handling an event with an instance method in the form, you already have a "this" parameter. Say something like this:

Public Class MyForm
    Inherits Form

    Private port As New SerialPort()

    Private Sub RegisterHandlers()
        AddHandler port.DataReceived, AddressOf ProcessData
    End Sub

    Private Sub ProcessData(ByVal sender As Object, ByVal e As EventArgs)
        If Me.InvokeRequired Then 
            'marshal to required thread
            Exit Sub
        End If

        'do stuff on the form thread
    End Sub
End Class
Gideon Engelberth
Yes, I do have a 'this' parameter, but I was trying to use it directly; evidently, a no-no. So I tried to get around it by making my event handler a static function, thus requiring a 'this' in the arg list. So yes, invoke is the key. thanks.
Joe