threading question

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

I found a way out, but it has a side effect: the class can now only be used
as member of a form, and not in a console application for example.

If there is a better solution I'd still like to know about it, because the
class handles communication between applications: there's no real reason
why it should only be used from within a form (I actually _did_ have test
and maintenance programs that ran as a console app in a previous version
of the project).


My current solution is to pass a reference of the parent form to the
class's constructor. Instead of a dummy control, it's now using the passed
form to call Invoke on.


Declaration of the class in the containing form becomes something like

Private m_Class As New TestClass(Me)

And in the class you find:

Public Sub New(ByRef Parent As Form)
m_Parent = Parent
End Sub

Private Delegate Sub d_FireTest()
Private Sub FireTest()
If m_Parent.InvokeRequired Then
m_Parent.Invoke(New d_FireTest(AddressOf FireTest))
Else
RaiseEvent TestEvent()
End If
End Sub
 
P

Peter Huang

Hi,

When did you create the control, if it is created in the working thread,
there is no need to invoke across thread.
Also your approach that pass a form is just ok, because the form is in the
UI thread, so that use form.invoke will invoke the function on the UI
thread.
If you still have any concern, please feel free to post here.

Best regards,

Peter Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.
 
L

Lucvdv

Hi,

When did you create the control, if it is created in the working thread,
there is no need to invoke across thread.

The control is created in the class constructor (sub New()), which means
it's created in the form's UI thread.

My problem was that ctl.InvokeRequired *always* returned False, whatever
thread it was called from, which meant some code in my app was executed in
the wrong thread while I expected the InvokeRequired/Invoke to take care of
that. I added sample code below to illustrate it.


The problem is solved, I just want to signal it because I found nothing in
the documetation that warns for this possibility, and someone else might be
bitten by it too.

Through some more experimenting, I found that [control].InvokeRequired
always returns False as long as the control hasn't been added to a form's
controls collection. The documentation says "Property Value: True if the
control's Handle was created on a different thread than the calling
thread", but just creating it in a form's UI thread isn't enough.



Sample code: the class is created in the form's constructor. The control
is created in the class's New(), so it is created by the UI thread.

FireTest calls InvokeRequired and Invoke on the control to ensure that the
event is fired in the UI thread, yet the event handler says it isn't.

The only place where FireTest is called is from within another thread, so
upon entry it should always log "InvokeRequired: True" in the debug pane,
followed by "InvokeRequired: False" when it's re-entered in the UI thread.
Instead, it reports False right away.

I included the full code, including auto-generated. You can create a new
standard windows app in VS.Net 2003 and paste everything below over the
generated code, it should work.


'----------------------------------------------------------------
Imports System.Threading

Public Class Form1
Inherits System.Windows.Forms.Form

Private tst As TestClass

#Region " Windows Form Designer generated code "

Public Sub New()
MyBase.New()

'This call is required by the Windows Form Designer.
InitializeComponent()

'Add any initialization after the InitializeComponent() call
tst = New TestClass
AddHandler tst.TestEvent, AddressOf TestEventHandler
End Sub

'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub

'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer

'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents Button1 As System.Windows.Forms.Button
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.Button1 = New System.Windows.Forms.Button
Me.SuspendLayout()
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(104, 80)
Me.Button1.Name = "Button1"
Me.Button1.TabIndex = 0
Me.Button1.Text = "Test"
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(292, 181)
Me.Controls.Add(Me.Button1)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)

End Sub

#End Region

Private Class TestClass
Public Event TestEvent()
Private thr As Thread
Private m_Ctl As Control

Public Sub New()
m_Ctl = New Control
End Sub

Private Delegate Sub d_FireTest()
Private Sub FireTest()
Debug.WriteLine(m_Ctl.InvokeRequired, "InvokeRequired")
If m_Ctl.InvokeRequired Then
m_Ctl.Invoke(New d_FireTest(AddressOf FireTest))
Else
RaiseEvent TestEvent()
End If
End Sub

Public Sub Test()
thr = New Thread(AddressOf ThreadProc)
thr.Start()
End Sub

Private Sub ThreadProc()
Thread.Sleep(250)
FireTest()
End Sub
End Class

Private Sub TestEventHandler()
If Me.InvokeRequired Then
MsgBox("Event handler not running in UI thread")
Else
MsgBox("Test event OK")
End If
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
tst.Test()
End Sub
End Class
 
P

Peter Huang

Hi Lucvdv,

When you attempt to access to the handle, the control's handle will be
created whether or not it is accessed from debugger or the running code.
Anyway this is a test, I think an official approach is to to use a control
on the form whose handle has been created as my last post said.

Best regards,

Peter Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.
 
L

lucvdv

Peter Huang said:
Hi Lucvdv,

When you attempt to access to the handle, the control's handle will be
created whether or not it is accessed from debugger or the running code.
Anyway this is a test, I think an official approach is to to use a control
on the form whose handle has been created as my last post said.

Of course, but it requires the class to know something about the form
it's going to be used in.

I solved it like I already said near the start of this thread: the New()
constructor of the class requires a form to be passed, and it calls
invoke on that form.


PS, Peter: are those "Did the response to your question in thread..."
mails auto-generated? I already considered the thread closed, my last
message was meant as a comment only ;)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top