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