1
我有一個線程運行以下tcpConnect方法。我希望在任何時候通過將Program.PrepareExit設置爲true來停止它。但是我的程序停留在:
Int32 bytes = stream.Read(data, 0, data.Length);
並且沒有真正反應Program.PrepareExit設置爲true。我怎麼能讓它總是退出,當我這樣說?如何讓TcpClient在線程中停止?
public static readonly Thread MyThreadTcpClient = new Thread(ThreadTcpClient);
private static void ThreadTcpClient() {
Connections.tcpConnect(ClientTcpIp, ClientTcpPort);
}
public static void Main() {
MyThreadTcpClient.Start();
.... some code....
Program.PrepareExit = true;
}
public static bool tcpConnect(string varClientIp, int varClientPort) {
var client = new TcpClient();
try {
client = new TcpClient(varClientIp, varClientPort) {NoDelay = true};
NetworkStream stream = client.GetStream();
var data = new Byte[256];
while (!Program.PrepareExit) {
Int32 bytes = stream.Read(data, 0, data.Length);
string varReadData = Encoding.ASCII.GetString(data, 0, bytes);
if (varReadData != "" && varReadData != "echo") {
VerificationQueue.EnqueueRelease(varReadData);
}
}
} catch (ArgumentNullException e) {
MessageBox.Show(e.ToString(), "ArgumentNullException");
tcpConnect(varClientIp, varClientPort);
} catch (SocketException e) {
MessageBox.Show(e.ToString(), "SocketException");
tcpConnect(varClientIp, varClientPort);
} catch (IOException e) {
if (e.ToString() != "Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.") {
}
MessageBox.Show(e.ToString());
tcpConnect(varClientIp, varClientPort);
} finally {
client.Close();
}
return false;
}
我只是需要這個線程被關閉,所以我可以關閉我的程序。只要不這樣做就可以使tcp服務器崩潰。 – MadBoy 2010-06-19 22:33:53
將其更改爲{IsBackground = true};它乾淨地退出:-)謝謝 – MadBoy 2010-06-19 22:40:56