await UDPClient.ReceiveAsync with timeout

bradgonesurfing picture bradgonesurfing · Sep 28, 2012 · Viewed 7.6k times · Source

I'm using UDPClient like below

dim c = New UDPClient(port)
client.CLient.ReceiveTimeout = 1
await client.ReceiveAsync()

However the await does not terminate or throw even though I have set a timeout. Is this normal behaviour?

Answer

Hans Passant picture Hans Passant · Sep 28, 2012

It is explicitly mentioned in the MSDN Library article for Socket.ReceiveTimeout:

Gets or sets a value that specifies the amount of time after which a synchronous Receive call will time out.

Emphasis added. You are doing the opposite of a synchronous receive when you use ReceiveAsync(). The workaround is to use a System.Timers.Timer that you start before the call and stop afterwards. Close the socket in the Elapsed event handler so the ReceiveAsync() method terminates with an ObjectDisposed exception.