locked
Cross-thread operation not valid

    Question

  •  public void listenerThread()

    {

    TcpListener tcpListener = new TcpListener(IPAddress.Any,1234);

    tcpListener.Start();

    while(true)

    {

    Socket handlerSocket = tcpListener.AcceptSocket();

    if (handlerSocket.Connected)

    {

    lbConnections.Items.Add(handlerSocket.RemoteEndPoint.ToString() + " connected.");

    lock (this)

    {

    alSockets.Add(handlerSocket);

    }

    ThreadStart thdstHandler = new

    ThreadStart(handlerThread);

    Thread thdHandler = new Thread(thdstHandler);

    thdHandler.Start();

    }

    }

    }

    I'm having an error Cross-thread operation not valid: Control 'lbConnections' accessed from a thread other than the thread it was created on.

    Please help! I don't know how to fix this

    Wednesday, May 10, 2006 10:01 PM

Answers

  • You must change the lbConnections handling:

    private delegate void ListenerCallback(string msg);

    private void ListenerFuction(string msg)

    {

    lbConnections.Items.Add(msg);

    }

    public void listenerThread()

    {

    ....

    if (handlerSocket.Connected)

    {

    lbConnections.Invoke(new ListenerCallback(ListenerFuction),new Object[] {handlerSocket.RemoteEndPoint.ToString() + " connected."});

    lock (this)

    ....

    }

    Markku

    Wednesday, May 10, 2006 10:31 PM

All replies

  • You must change the lbConnections handling:

    private delegate void ListenerCallback(string msg);

    private void ListenerFuction(string msg)

    {

    lbConnections.Items.Add(msg);

    }

    public void listenerThread()

    {

    ....

    if (handlerSocket.Connected)

    {

    lbConnections.Invoke(new ListenerCallback(ListenerFuction),new Object[] {handlerSocket.RemoteEndPoint.ToString() + " connected."});

    lock (this)

    ....

    }

    Markku

    Wednesday, May 10, 2006 10:31 PM
  • thanks very much, do I always have to do this everytime I have a multithreaded app?

    I'm a delphi programmer so I'm just learning .NET 2

     

    Fahd

    Wednesday, May 10, 2006 11:21 PM
  • no, there is a property

    InvokeRequired (from Control)

    which tells you if the thread is allowed to access to control.

    Thursday, May 11, 2006 12:32 AM
  • Other trick is set app property

    CheckForIllegalCrossThreadCalls = false;

    Thursday, May 11, 2006 7:31 AM
  • Setting CheckForIllegalCrossThreadCalls to false only hides the symptoms of the problem - the underlying cross-thread problem is still there.

    You'd only want to set this property to quickly get a .NET 1.1 app quickly running when building in 2.0, and should get around to using the Invoke to call on the correct thread.

    Thursday, May 11, 2006 11:50 AM