Home All Groups Group Topic Archive Search About

multi threading error

Author
27 Feb 2006 3:19 AM
iwdu15
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
--
-iwdu15

Author
27 Feb 2006 11:26 AM
Larry Lard
iwdu15 wrote:
> 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

--
Larry Lard
Author
27 Feb 2006 3:19 PM
iwdu15
thanks for the info, il keep that in mind! also thanks for the quick
response, it works great
--
-iwdu15