J'ai un thread qui s'exécute suivant la méthode tcpConnect. Je souhaite l'arrêter à tout moment en définissant Program.PrepareExit sur true. Cependant mon programme est bloqué à:
Int32 bytes = stream.Read(data, 0, data.Length);
et ne réagit pas vraiment à Program.PrepareExit réglé sur true. Comment puis-je faire pour arrêter de fumer quand je le dis?Comment faire pour que TcpClient s'arrête dans un thread?
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;
}
J'ai juste besoin que ce thread soit arrêté pour que je puisse fermer mon programme. La connexion Tcp peut être abandonnée tant qu'elle ne le fait pas de manière à pouvoir planter le serveur TCP. – MadBoy
l'a changé en {IsBackground = true}; et il sort proprement :-) Merci – MadBoy