0

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

Joe
  • 71
  • 10
  • If you are concerned that events are _always_ triggered on another thread, rest easy, most of the time they won't be. Especially for events triggered by user action. – John Knoeller Jan 28 '10 at 01:18

2 Answers2

1

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.
  • 58,739
  • 8
  • 81
  • 86
1

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
  • 6,095
  • 1
  • 21
  • 22
  • 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 Jan 28 '10 at 01:49