2010-06-13 36 views
1

如何解決「Control.Invoke必須用於與一個獨立的線程創建控件交互」錯誤異常如何解決Winforms Control.Invoke錯誤?

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(); 
+2

編輯代碼片段以顯示失敗的代碼。 – 2010-06-13 09:39:07

+0

你肯定確定它是導致異常的這一點代碼嗎?實際上(隱式地)創建UI控件的唯一地方是通過調用MessageBox.Show,但我迄今認爲這種方法不必在UI(「main」)線程上運行。你真的在程序中使用多線程嗎? – stakx 2010-06-13 10:13:32

回答

0

這樣做出來嗎?這聽起來像你在某種回調,但(由於線程親和力),你可以只有談話控制其相關的線程。所以:

string newAnswer = LongComplexCode(); // on worker thread here 
someControl.Invoke((MethodInvoker) delegate { 
    /* your work here, e.g. */ 
    someControl.Text = newAnswer; // on UI thread here 
}); 
+0

// My Coding is, Socket serverSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); serverSocket.Bind(新的IPEndPoint(IPAddress.Loopback,portNo)); serverSocket.Listen(5); 套接字客戶端= serverSocket.Accept(); MessageBox.Show(「客戶端連接」); //發送給客戶端 NetworkStream ns = new NetworkStream(client); StreamWriter writer = new StreamWriter(ns); writer.AutoFlush = true; write.WriteLine(sb.ToString()); //從客戶端接收 NetworkStream nets = new NetworkStream(client); StreamReader reader = new StreamReader(nets); string clientIPAddress = reader.ReadLine(); – 2010-06-13 08:57:57