Simple cross thread problem (I think)

G

Guest

I ran into a threading issue with vb.net 2005.

So I did some research and found out I could do one of two things.

I could use the following(Which I'm not a big fan of)

Dim ctl As Control
For Each ctl In Me.Controls
If TypeOf (ctl) Is TextBox Or TypeOf (ctl) Is Label Then
Control.CheckForIllegalCrossThreadCalls = False
End If
Next

or I have to use a delegate and call it like so

I like the secondary idea but I can't get my head around it. It's probably
simple and I've over complicated it but all I need to do is react to a raise
event call from a class on a form.

I have looked at all kinds of examples but I'm don't see how it applies to
my situation.

Does anyone have an example of what I need to do?
I just want to update labels and textboxes on my form when the event is
raised.

Here's the sub as it is now
Private sub mMachCtl_NotDecoded ()Handles mMachCtl.NoDecoded
txtColor.Text = "Error"
txtLotNum.Text = "Error"
Dim ctl as control
for each ctl in me.controls
if typeof ctl is label or typeof ctl is textbox then
ctl.backcolor = color.red
end if
loop
End Sub

so how do I setup the delegate, and something to make that happen?
 
M

Marc Gravell

The first idea is a bad one; look carefully: you aren't changing an
instance, but rather the static Control class; don't do this. Stick to
delegates via BeginInvoke.

Re the main question, I'm not fluent enough in VB.Net to give you a
satisfactory answer (although I can answer in c# if you like?) - so: any
VBers to pick that up?

Marc
 
C

Claes Bergefall

Try this:

Private Sub mMachCtl_NotDecoded() Handles mMachCtl.NoDecoded
If Me.InvokeRequired Then
Dim fn As New MethodInvoker(AddressOf OnmMachCtl_NotDecoded)
Me.Invoke(fn)
Else
OnmMachCtl_NotDecoded()
End If
End Sub

Private Sub OnmMachCtl_NotDecoded()
txtColor.Text = "Error"
txtLotNum.Text = "Error"
For Each ctl As Control In Me.Controls
If TypeOf ctl Is Label Or TypeOf ctl Is TextBox Then
ctl.BackColor = Color.Red
End If
Next
End Sub

/claes
 
P

Patrice

The big picture may help. I'm not sure what you are trying to do and what
the issue you have is. The main problem is likely that you have to use the
"Invoke" method to update the UI (the UI needs to be updated from the UI
thread).

If 2.0 the new BackgroundWorker component may also help.
 
G

Guest

Thank you to everyone who responded. I appreciate the help. The snippet that
Claes provided did exactly what I needed.

My class raises the event and by using the method invoker I can execute the
correct subroutine on the forms thread.

Exactly what I was looking for and again thanks to all of you.

Pat
 

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

Similar Threads


Top