multi threading error

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • iwdu15

    #1

    multi threading error

    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.GetHost Entry(Net.Dns.G etHostName).Add ressList(0)

    ep = New IPEndPoint(Home IP, PortNumber)

    ListenSocket = New Socket(AddressF amily.InterNetw ork,
    SocketType.Stre am, ProtocolType.Tc p)

    ListenSocket.Bi nd(ep)
    ListenSocket.Li sten(1)
    ListenSocket.Be ginAccept(Addre ssOf ListenCallBack, Nothing)

    Catch ex As Exception

    Call WriteErrors(ex. Message, "ListenBegi n")

    Finally

    SyncLock Me

    ''error here
    Me.Text = HomeIP.ToString

    End SyncLock

    End Try

    End Sub
    --
    -iwdu15
  • Larry Lard

    #2
    Re: multi threading error


    iwdu15 wrote:[color=blue]
    > 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?[/color]

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

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

    Quick fix: change

    SyncLock Me
    Me.Text = HomeIP.ToString
    End SyncLock

    to

    Me.Invoke(New StringParameter Delegate(Addres sOf TextSetter), _
    New Object() {HomeIP.ToStrin g})

    add

    Delegate Sub StringParameter Delegate(ByVal value As String)

    at form level

    and add

    Private Sub TextSetter(ByVa l value As String)
    Me.Text = value
    End Sub

    --
    Larry Lard

    Comment

    • iwdu15

      #3
      Re: multi threading error

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

      Comment

      Working...