D
Dr. J
How to terminate a blocked thread?
In my form's "load" I launch a TCP listening thread that stays in an
infinite loop waiting for incoming TCP packets. In this form's "closing" I
try to terminate this thread by calling the "Abort" funcion. But the thread
does not terminate and after the form is closed this thread keeps running at
blocked state. Basically the application keeps running because this thread
does not terminate while blocked. The task manager shows the application
running even after closing of the form.
My question is what is proper method of shutting down blocked threads in an
application? Below is my code snippet to illustrate this situation.
Thanks in advance,
----------------------------------------------
// thread to listen synchronously in an infinite loop
public void ListenThread()
{
IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
TcpListener tcpl = new TcpListener(ipAddress, 49152);
tcpl.Start();
while(true)
{
Socket newSocket = tcpl.AcceptSocket();
// Blocked here
if(newSocket.Connected)
{
// do work here
newSocket.Close();
}
}
}
// launch the thread on "load"
Thread TcpListen;
private void Form1_Load(object sender, System.EventArgs e)
{
TcpListen = new Thread(new ThreadStart(ListenThread));
TcpListen.Start();
}
// try to terminate the thread in "closing"
private void Form1_Closing(object sender,
System.ComponentModel.CancelEventArgs e)
{
if(TcpListen.IsAlive)
{
TcpListen.Abort (); // won't terminate the thread
}
}
In my form's "load" I launch a TCP listening thread that stays in an
infinite loop waiting for incoming TCP packets. In this form's "closing" I
try to terminate this thread by calling the "Abort" funcion. But the thread
does not terminate and after the form is closed this thread keeps running at
blocked state. Basically the application keeps running because this thread
does not terminate while blocked. The task manager shows the application
running even after closing of the form.
My question is what is proper method of shutting down blocked threads in an
application? Below is my code snippet to illustrate this situation.
Thanks in advance,
----------------------------------------------
// thread to listen synchronously in an infinite loop
public void ListenThread()
{
IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
TcpListener tcpl = new TcpListener(ipAddress, 49152);
tcpl.Start();
while(true)
{
Socket newSocket = tcpl.AcceptSocket();
// Blocked here
if(newSocket.Connected)
{
// do work here
newSocket.Close();
}
}
}
// launch the thread on "load"
Thread TcpListen;
private void Form1_Load(object sender, System.EventArgs e)
{
TcpListen = new Thread(new ThreadStart(ListenThread));
TcpListen.Start();
}
// try to terminate the thread in "closing"
private void Form1_Closing(object sender,
System.ComponentModel.CancelEventArgs e)
{
if(TcpListen.IsAlive)
{
TcpListen.Abort (); // won't terminate the thread
}
}