tags:

views:

54

answers:

1

How to solve the "Control.Invoke must be used to interact with controls created on a separated thread" Error Exception

        Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
        serverSocket.Bind(new IPEndPoint(IPAddress.Loopback, portNo)); 
        serverSocket.Listen(5); 
        Socket client = serverSocket.Accept(); 
        MessageBox.Show("Client Connected"); 

        //Sent to Client 
        NetworkStream ns = new NetworkStream(client); 
        StreamWriter writer = new StreamWriter(ns); 
        writer.AutoFlush = true; 
        writer.WriteLine(sb.ToString()); 

        //Receive from Client NetworkStream 
        Stream nets = new NetworkStream(client); 
        StreamReader reader = new StreamReader(nets); 
        string clientIPAddress = reader.ReadLine();
A: 

By doing what it says? It sounds like you're in some kind of callback, but (due to thread affinity) you can only talk to controls on their associated thread. So:

string newAnswer = LongComplexCode(); // on worker thread here
someControl.Invoke((MethodInvoker) delegate {
    /* your work here, e.g. */
    someControl.Text = newAnswer; // on UI thread here
});
Marc Gravell
//My Coding is,Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);serverSocket.Bind(new IPEndPoint(IPAddress.Loopback,portNo));serverSocket.Listen(5);Socket client = serverSocket.Accept();MessageBox.Show("Client Connected");//Sent to ClientNetworkStream ns = new NetworkStream(client);StreamWriter writer = new StreamWriter(ns);writer.AutoFlush = true;writer.WriteLine(sb.ToString());//Receive from ClientNetworkStream nets = new NetworkStream(client);StreamReader reader = new StreamReader(nets);string clientIPAddress=reader.ReadLine();
omn ohnmar