L
Lucvdv
A class in my app starts a new thread, and fires events from within that
thread.
The result, if nothing is done to prevent it, is that the events are
executed in the wrong thread in a form having a member of that class.
A user class doesn't have an Invoke method: how can I make the worker
thread invoke the events in the main UI thread that created the class?
The approach I originally built in does NOT work (I found this out only by
accident, because a Windows.Forms.Timer I started in one of the the event
handlers never generated any Tick events.)
I had added a dummy control to the class:
Private Shared m_ctl As New Control
and wrapped all events in functions:
Private Delegate Sub d_RaiseConnect()
Private Sub RaiseConnect()
If m_ctl.InvokeRequired Then
m_ctl.Invoke(New d_RaiseConnect(AddressOf RaiseConnect))
Else
RaiseEvent OnConnect()
End If
End Sub
The events are _still_ being fired from the wrong thread: Me.InvokeRequired
is True in the event handler in the form containing the class.
Upon entry of RaiseConnect in the worker thread, m_ctl.InvokeRequired is
False.
I started thinking later that this is probably correct, as the control
doesn't have a window, so there's no need to use Invoke to access it, but
when I make it a TextBox instead of just "Control", it *still* says
InvokeRequired = False.
Making it an instance member instead of shared, or instantiating it in the
class constructor instead of through "as new", makes no difference either.
thread.
The result, if nothing is done to prevent it, is that the events are
executed in the wrong thread in a form having a member of that class.
A user class doesn't have an Invoke method: how can I make the worker
thread invoke the events in the main UI thread that created the class?
The approach I originally built in does NOT work (I found this out only by
accident, because a Windows.Forms.Timer I started in one of the the event
handlers never generated any Tick events.)
I had added a dummy control to the class:
Private Shared m_ctl As New Control
and wrapped all events in functions:
Private Delegate Sub d_RaiseConnect()
Private Sub RaiseConnect()
If m_ctl.InvokeRequired Then
m_ctl.Invoke(New d_RaiseConnect(AddressOf RaiseConnect))
Else
RaiseEvent OnConnect()
End If
End Sub
The events are _still_ being fired from the wrong thread: Me.InvokeRequired
is True in the event handler in the form containing the class.
Upon entry of RaiseConnect in the worker thread, m_ctl.InvokeRequired is
False.
I started thinking later that this is probably correct, as the control
doesn't have a window, so there's no need to use Invoke to access it, but
when I make it a TextBox instead of just "Control", it *still* says
InvokeRequired = False.
Making it an instance member instead of shared, or instantiating it in the
class constructor instead of through "as new", makes no difference either.