multi threading error

G

Guest

hi, im writing a program with multiple threads, and in one of the secondary
threads, i need to access the main form...but the code i wrote throws errors
saying i cant do this. is there anyway i can simply change the text on the
main form from another thread?

my code:

Private Sub ListenBegin()

Try

Dim ep As IPEndPoint

HomeIP = Net.Dns.GetHostEntry(Net.Dns.GetHostName).AddressList(0)

ep = New IPEndPoint(HomeIP, PortNumber)

ListenSocket = New Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp)

ListenSocket.Bind(ep)
ListenSocket.Listen(1)
ListenSocket.BeginAccept(AddressOf ListenCallBack, Nothing)

Catch ex As Exception

Call WriteErrors(ex.Message, "ListenBegin")

Finally

SyncLock Me

''error here
Me.Text = HomeIP.ToString

End SyncLock

End Try

End Sub
 
L

Larry Lard

iwdu15 said:
hi, im writing a program with multiple threads, and in one of the secondary
threads, i need to access the main form...but the code i wrote throws errors
saying i cant do this. is there anyway i can simply change the text on the
main form from another thread?

Short answer: Never invoke any method or property on a control created
on another thread

Background reading:
<http://yoda.arachsys.com/csharp/threads/winforms.shtml>

Quick fix: change

SyncLock Me
Me.Text = HomeIP.ToString
End SyncLock

to

Me.Invoke(New StringParameterDelegate(AddressOf TextSetter), _
New Object() {HomeIP.ToString})

add

Delegate Sub StringParameterDelegate(ByVal value As String)

at form level

and add

Private Sub TextSetter(ByVal value As String)
Me.Text = value
End Sub
 
G

Guest

thanks for the info, il keep that in mind! also thanks for the quick
response, it works great
 

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