Can I set the timeout for UdpClient in C#?

Jack picture Jack · Feb 17, 2010 · Viewed 48.6k times · Source

I am wondering whether I can set a timeout value for UdpClient receive method.

I want to use block mode, but because sometimes udp will lost packet, my program udpClient.receive will hang there forever.

any good ideas how I can manage that?

Answer

sep15ms picture sep15ms · Apr 16, 2011

There is a SendTimeout and a ReceiveTimeout property that you can use in the Socket of the UdpClient.

Here is an example of a 5 second timeout:

var udpClient = new UdpClient();

udpClient.Client.SendTimeout = 5000;
udpClient.Client.ReceiveTimeout = 5000;

...