有什麼辦法可以在C#方法中擁有不可變參數嗎?下面我給一些messenger應用程序提供了一些代碼,這些代碼給了我一些問題。這個想法是有一臺服務器可以處理多個客戶端。該代碼通過創建TcpListener
來監視傳入連接,獲取底層TcpClient
(通過NetworkStream
作爲字符串發送)的IP地址,啓動一個處理來自該客戶端的消息的新線程,然後監聽更多連接。主要問題是client
對象被傳遞到新的Thread
後,主代碼將循環並在等待另一個連接時將值client
設置爲null
。C# - 不可變的方法參數
錯誤類型:System.InvalidOperationException
錯誤消息:The operation is not allowed on non-connected sockets.
這是什麼對我說的是,TcpClient
的的handleMessages
線程內在價值正受到該線程的.Start()
方法啓動後會發生什麼client
。
這裏是我的代碼:
private void watchForConnections()
{
TcpListener listener = new TcpListener(IPAddress.Any, this.Port); //Listener that listens on the specified port for incoming clients
listener.Start();
TcpClient client = new TcpClient();
do
{
client = listener.AcceptTcpClient(); //Wait for connection request
StreamReader reader = new StreamReader(client.GetStream());
string clientIP = reader.ReadLine(); //Use the StreamReader to read the IP address of the client
RelayMessage("SERVER_NEW_" + clientIP + "_" + DateTime.Now.ToString("HH:mm:ss")); //Tell all machines who just connected
Thread messageWatcher = new Thread(() => handleMessages(client));
messageWatcher.Start(); //Start new thread to listen for messages from that specific client
} while (AllowingConnections == true);
listener.Stop();
}
private void handleMessages(TcpClient _client)
{
using (StreamReader readMsg = new StreamReader(_client.GetStream())) //I get the error here
using (StreamWriter writeMsg = new StreamWriter(_client.GetStream())) //And here
{
//Handle messages from client here
}
}
我的問題:有什麼辦法可以在handleMessages
參數將不被會發生什麼方法之外有什麼影響?迄今爲止,我的研究並沒有涉及到這個問題,或者任何類似的問題。我需要的是有點像ref
參數的反面。也許我只是沒有在尋找正確的東西。我不知道我是否解釋正確。
用繩子又如:
string data = "hello";
Thread doStuff = new Thread(() => DoStuff(data)); //Value of data is equal to: "hello"
doStuff.Start();
data = "goodbye"; //I want the value of the string in the doStuff thread to still be: "hello", not "goodbye" (Don't reflect changes made to string after thread is started/method is called)
如果有什麼不清楚,請讓我知道!我可能和你一樣困惑!
UPDATE /解決方案: 的人誰需要它的未來,這是問題是如何解決的,按照維魯的回答是:
Thread messageWatcher = new Thread(() => handleMessages(client.Clone());
你爲什麼不這樣稱呼它複製'DoStuff(string.Copy(數據))' ,從而創建一個新的'數據'的無關副本? – dotNET
創建副本。 'var copy = data'? –
這已經在這裏討論:http://stackoverflow.com/questions/2339074/can-parameters-be-constant –