I'm trying to maintain some horrible VB to get concurrency.
I want to delegate some Maths code to a thread and have it raise an event with EventArgs which contains a structure with the information with which to update a form. In the UI event handler, I'm using BeginInvoke so as not to block the thread because the UI update takes quite a bit of time, but the thread needs to carry on with the next set of Maths.
The previous programmer implemented a timer to call the Maths code and there are a gnats swarm of global variables which represent the results; no way can I implement data locking, it's too big change. The problem with the timer solution is that the Maths code can't run while the UI is being updated (at a slower rate). I've also considered splitting up the UI code across many timer events but this is also quite irksome to achieve to get a balance across the cycles.
Are the EventArgs thread safe i.e. if the UI starts to use the passed EventArgs and the thread generates another event, OR should the UI clone a copy before control is transferred to the UI thread ?
I've written some test code which looks like this.
Private Observed As UIDelegatePattern.Observed
Private Delegate Sub ProcessDelegate(ByVal sender As Object, ByVal e As UIDelegatePattern.Observed.ProcessEventArgs)
Private Sub Render(ByVal sender As Object, ByVal e As UIDelegatePattern.Observed.ProcessEventArgs)
If Me.InvokeRequired Then
Dim d As ProcessDelegate = New ProcessDelegate(AddressOf Render)
' invoke on the UI thread asynchronously
Me.BeginInvoke(d, New Object() {sender, e})
Else
' prevent event overflow by removing the handler before the long rendering activity
RemoveHandler Observed.EventHandler, AddressOf Render
' simulate many controls updates
For i As Integer = 0 To 1000
Me.Label1.Text = e.Message
Next
Me.Update()
Me.Refresh()
Application.DoEvents()
' add the handler back in for next time
AddHandler Observed.EventHandler, AddressOf Render
End If
End Sub
You've got a lot of information, and possible some other questions implied, in that post. But to be specific, as long as the class that is raising the event creates a new EventArgs on each notification then you are fine and do not need to copy the EventArgs in the event listener.