Question about threads

  • Thread starter Thread starter C.A.
  • Start date Start date
C

C.A.

I am looking at the Creating a Multi-User TCP Chat Application
and I do not understand something. They say that we cannot
directly add the received text to the textbox of the client because
the receiving thread from the network stream is not the main thread.
The solution offered is to use the me.invoke method to switch to
the main thread, i.e.

Me.Invoke(New DisplayInvoker(AddressOf Me.DisplayText), params)

I can't see how this switches back to the main thread, Me refers to
the current instance, which is not the main thread,
AddressOf Me.DisplayText is the address of DisplayText in the current
thread ?
 
First, define an instance variable for your main form in your thread class:

Private m_MainForm as MyMainFormClass

When you create your thread, pass in the main form instance and store in
m_MainForm. Now your thread has an instance to communicate with.

Next, define a delegate in your thread class:

Private Delegate Sub _SendString_Delegate(ByVal theString As String)

Also, create a method in your thread class for sending a string to the main
thread:

Public Sub SendString(ByVal theLabel As String)

Dim Parameters(0) As Object

Parameters(0) = theString

Try

m_MainForm.Invoke(New _SendString_Delegate(AddressOf
m_MainForm.DisplayText), Parameters)

Catch ex As Exception

End Try

End Sub


Execute this method in your thread whenever you wish to send a string

Finally, in your main form, add a method "DisplayText(byval theString as
String)".
 
So Me will refer to the form thread, so that's OK.

Are there any other ways to do this, i.e. if I have a second thread
and I want to update information in the form, this is not thread safe,
so I can use me.invoke, Can I use SyncLock, or events?
Would this work:
assume textbox1.text is on a form, and we are on a different thread,
can we do this safely:

SyncLock
textbox1.text="1234"
end SyncLock

If so, why bother with delegate/invoke, this is much simpler to code?
 
The way I understand it, you might get deadlocked on your main thread if you
do that. Invoking the delegate should ensure this doesn't happen.

I'm not 100% sure either whether invoking the delegate from multiple threads
is safe. I assume the invocations are queued somewhere and executed on your
main thread one at a time. To be safe you could synchronise in your main
thread, but someone with more knowledge (my program only uses a single
worker thread) about threading might be able to help and possibly avoid the
synchronisation overhead.
 

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

Back
Top