need help with threads

  • Thread starter Thread starter Tom L
  • Start date Start date
T

Tom L

I'm using a listener that is using threads (for a messaging type app).. The
listener is declared on my form.. then in my little socket server class,
I've got..

Do
SyncLock tThread
If ServerOn = True Then
ProcessServer()
End If

If ClientOn = True Then
ProcessClient()
End If

tThread.Sleep(SweepTime)
End SyncLock
Loop

When ProcesServer is called, it triggers off the dataarrival event. For
testing purposes, I had it outputing in a mgbox, which worked fine.
But then I want to take the data and send it back to the form, when I do
that I get an error:

The action being performed on this control is being called from the wrong
thread. You must marshal to the correct thread using "Control.Invoke or
Control.BeginInvoke to perform this action."

stack trace:
at System.Windows.Forms.TreeNode.Realize()
at System.Windows.Forms.TreeNodeCollection.Add(TreeNode node)
at isrMessaging.frmCommunicator.Server_DataArrival(String Data, Thread thrd)

As you can tell, I'm trying to dump the response into a treeview node

Can anyone offer some help on how I get this to work? As you can tell, I'm
very new to threads..

Thanks
 
Hi Tom,

Actually, updating windows forms controls, such as the treeview control
in your example, from threads other than the one that created the
control is inherently not thread safe.

So these controls must be updated only from the thread that
created the control. To update the controls from another thread
use the Control.Invoke() method.

In your example, the frmCommunicator.Server_DataArrival event handler
is probably being called from another thread, and when it tries to
update the TreeView control, you get the error.
You can use the Control.InvokeRequired property to check whether the
caller is another thread.

For more details, please check the link below:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnforms/html/winforms06112002.asp

Regards,
Aravind C
 
Back
Top