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?