[2005] cross thread operations - events... any nice way to do this?
I'm new to .NET 2
I have several events that get raised from a thread that is different from my winform thread. I don't want to check InvokeRequired for every control. So I'm guessing it's best to just let the event be raised via a callback on the winform thread instead.....
I havent used .NET in a while so I cant remember things :D
When I'm binding my event handler in the new thread, is there a way to bind the event so it would be called in the winform thread and not in the current thread?
Re: [2005] cross thread operations - events... any nice way to do this?
No there is not an automatic way to have the event called in the winform event. If you wrote the object raising the event you could manage something on the RaiseEvent end otherwise you need to check InvokeRequired. I'm not sure what you mean by 'for every control' though.
Re: [2005] cross thread operations - events... any nice way to do this?
You should take note of how classes like the System.Timers.Timer and FileSystemWatcher work. They have a SynchronisingObject property that tells them what thread to raise their events on. You could use .NET Reflector to see exactly how it's implemented but at a guess it would be something like this:
vb Code:
Public Event SomeEvent(ByVal sender As Object, ByVal e As EventArgs)
Protected Delegate Sub EventRaiser(ByVal e As EventArgs)
Protected Sub OnSomeEvent(ByVal e as EventArgs)
If Me.SynchronizingObject IsNot Nothing AndAlso _
Me.SynchronizingObject.InvokeRequired Then
'Raise the event on the thread that owns the synchronising object.
Me.SynchronizingObject.Invoke(New EventRaiser(AddressOf OnSomeEvent), e)
Else
'Raise the event on the current thread.
RaiseEvent(Me, e)
End If
End Sub