[.net] thread.Abort() not killing blocked thread

Started by
1 comment, last by jef396 19 years, 6 months ago
I am writing a program that uses UDP to do a locator type service. ie broadcasts a packet on the network, everything listening for it replies. So I have an app that does the broadcast fine, but before it does it starts up a thread that acts as the server. That server is stuck in a while(true) loop constantly reading from a socket. It works fine, when I send a packet and get a response, it is handled correctly. The issue arrises when I try to exit the form. I click my exit button which calls

if(udpthread != null) 
{
	udpthread.Abort();
	udpthread.Join();
}
this.Close();




that should signal to the thread an AbortException, which it should catch and then terminate. But that never happens, looking in the debugger (and the join commmand not finishing) I can tell that the read thread is still in the blocking state. According to MSDN the abort exception should interupt a blocked thread... so what am I doing wrong? The thread is created with:

if(udpthread == null) 
{
	try
	{		
		//Starting the UDP Server thread.
		udpthread = new Thread(new ThreadStart(udplisten));
		udpthread.IsBackground = true;
		udpthread.Start();
	}
	catch (Exception e)
	{
		udpthread.Abort();
	}
}




and the function is:

private void udplisten() 
{

	try 
	{
		Socket soUdp = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
		IPEndPoint localIpEndPoint = new IPEndPoint(IPAddress.Any, udpport);
		soUdp.Bind(localIpEndPoint);
		this.label1.Text = "";
		while (true)
		{
			Byte[] received = new Byte[256];
			IPEndPoint tmpIpEndPoint = new IPEndPoint(IPAddress.Any, udpport);

			EndPoint remoteEP = (tmpIpEndPoint);

			int bytesReceived = soUdp.ReceiveFrom(received, ref remoteEP);
			this.label1.Text += bytesReceived + " ";
		}
	} 
	catch (Exception e)
	{
		//				udpthread.Abort();
		return;
	} 
	finally 
	{
			
	}

}





Does anyone know what is wrong?
Advertisement
I don't see anything wrong with your code, but why not put just the receiving function in a try block instead of the whole udplisten function. Then you can set a time out on it, and just have it continue with the loop when a timeout exception is caught or return when an abort exception is caught.
Here's some code:

				while (true)				{					Byte[] received = new Byte[256];					IPEndPoint tmpIpEndPoint = new IPEndPoint(IPAddress.Any, udpport);					EndPoint remoteEP = (tmpIpEndPoint);					try					{						int bytesReceived = soUdp.ReceiveFrom(received, ref remoteEP);					}					catch (SocketException ee)					{						if (10035 == ee.ErrorCode)						{							//timed out						}					}					this.label1.Text += bytesReceived + " ";				}

This topic is closed to new replies.

Advertisement