• C# socket broadcasts sent out on a random interface

    Today I was working on a service discovery algoritm using C# sockets sending and receiving broadcast packets. It worked fine when the computer in use is having just one network interface, but testing on a different machine, I found out that even while binding the socket to IPAddress.Any, it still picks just one of the interfaces to send out the packet.

    The solution is to use the ‘do not route’ option on the socket. The code becomes:

    sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    iep1 = new IPEndPoint(IPAddress.Broadcast, 9050);
    string hostname = Dns.GetHostName();
    data = Encoding.ASCII.GetBytes(hostname);
    sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
    sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
    sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontRoute, true);
    sock.Bind(new IPEndPoint(IPAddress.Any, 9051));
    sock.SendTo(data, iep1);

  • .NET serial port datareceived fires slow?

    Today I discovered something that had been a pain in my .NET project for weeks. If you work with the SerialPort component in .NET 4 you might notice that in some cases it takes several hundreds of milliseconds between data arriving in your serial port buffer, and your datareceived handler being called. I couldn’t trace this until I started doing some debugging with a port monitor like HDD free serial port monitor, and reading through this threadat MSDN forums. I figured that the delay occurred when the handler was queued for execution through the threadpool. Under certain circumstances the threadpool creates a new thread in order to handle your routine, and apparently this may take up to 500 milliseconds.

    So what you should do is use Threadpool.SetMinThreads() at program startup to increase the minimum number of threads to a suitable value, and there you are! No more delay!

    Thanks to Alex Pinsker and ‘nobugz’.