Ending a thread safely when using UDP Receive

client.Receive will return an empty byte[] when the connection is closed. You should just have to close the connection and change the provided code to:

private void RecieveChallenge()
{
    UdpClient client = new UdpClient(26000);
    IPEndPoint remoteIp = new IPEndPoint(IPAddress.Any, 0);

    Byte[] receivedBytes = client.Receive(ref remoteIp);
    if (receivedBytes == null || receivedBytes.Length == 0)
        return;
    string ipAddress = Encoding.ASCII.GetString(receivedBytes);
}

Though you'll probably want RecieveChallenge to return a boolean indicating whether it is closed or not (of course ignoring the fact that your thread will only ever receive one message).


Instead of Receive(), you can use BeginReceive()/EndReceive() - it is an asynchronous alternative.

See MSDN: http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.beginreceive.aspx

These methods use a common APM (asynchronous programming model) of .NET.


If you want to wait for it to end before continue on your current thread, you can use

recieveDataThread.Join();

Otherwise, thread closes as soon as the last line completes.

If you want to end it early, you can use

recieveDataThread.Abort(); 

from another thread.