Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

await UDPClient.ReceiveAsync with timeout

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?

like image 525
bradgonesurfing Avatar asked Sep 28 '12 10:09

bradgonesurfing


People also ask

Is there a receivetimeout property in udpclient?

There is a ReceiveTimeout property you can use. Actually, it appears that UdpClient is broken when it comes to timeouts. I tried to write a server with a thread containing only a Receive which got the data and added it to a queue. I've done this sort of things for years with TCP.

What is the problem with udpclient receiveasync?

That title is a little weird, but I have a UdpClient and it uses ReceiveAsync to listen for response from the remote endpoint after a SendAsync. The problem is that the remote endpoint is a very flimsy IoT device that will either close the connection, or never reply.

What is a timeout in httpclient?

The timeout is defined at the HttpClient level and applies to all requests made with this HttpClient; it would be more convenient to be able to specify a timeout individually for each request. The exception thrown when the timeout is elapsed doesn’t let you determine the cause of the error.

How can I await an object but with a timeout?

Say you have an awaitable object, and you want to await it, but with a timeout. How would you build that? What you can do is use a when_any -like function in combination with a timeout coroutine. For C# this would be something like await Task.WhenAny ( DoSomethingAsync (), Task.Delay (TimeSpan.FromSeconds (1)));


2 Answers

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.

like image 105
Hans Passant Avatar answered Sep 28 '22 10:09

Hans Passant


Yes. The asynchronous methods on Socket do not implement the timeouts. If you need timeouts on asynchronous operations, you have to create them yourself (e.g., using Task.Delay and Task.WhenAny).

like image 28
Stephen Cleary Avatar answered Sep 28 '22 10:09

Stephen Cleary