Bakery
Bakery

Reputation: 406

Handle Socket.ReceiveFrom with timeout without spamming console

I am writing a ServerLocator that basically broadcast a port to find a server which will respond with an IPEndPoint and I need the search to be able to timeout if nothing is found on the current IPHost and then move on with the next one.

Right now I am doing something like this (I have removed some parts of this code so it only includes what is needed to display my problem. There is also some client bindings going on here)

string serverIp = string.Empty;
while(string.isNullOrEmpty(serverIp))
{   
    foreach (IPAddress adress in ipHosts.AddressList)
    {
        using(Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
        {
            try
            {
                client.ReceiveFrom(buffer, ref tempRemoteEP);

                //Get server IP
                serverIp = tempRemoteEP.ToString().Split(":".ToCharArray(), 2)[0];
                break;
            }
            catch(SocketException e)
            {
                // We expect connection attempt to time out if we cant find any server on this port and nic. Just continue with the next
                if (e.SocketErrorCode == SocketError.TimedOut)
                {
                    continue;
                }
            }
        }
    }
}

This works as expected except that the console gets spammed with:

A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll

Is there a good way to handle exceptions like this without spamming the console? Or could I handle this in some other way to be able to avoid the need of exception from timeout?

Thanks.

Upvotes: 3

Views: 3522

Answers (1)

default
default

Reputation: 11635

There's really no need to worry about this if the program keeps running, there's a lot of these exceptions being sent in a program. See this article for more on "First time exceptions".

Also check this link to see how you can configure Visual Studio on how to handle the exceptions. If you configure these you can break (instead of continue) on the exceptions and see what's really going on. However, do note that hiding the exceptions does not seem to work in debug, see here or here But as @Cipi pointed out, it should not be visible in Release.

Upvotes: 1

Related Questions