await UDPClient.ReceiveAsync with timeout

安稳与你 提交于 2019-11-28 08:40:41

问题


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?


回答1:


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.




回答2:


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).




回答3:


I had this issue recently and this is how I solved it:

async Task Listen(IPEndPoint ep, int timeout)
{
    using (var udp = new UdpClient(ep))
    {
        var result = await Task.Run(() =>
        {
            var task = udp.ReceiveAsync();
            task.Wait(timeout);
            if (task.IsCompleted)
            { return task.Result; }
            throw new TimeoutException();
        });

        Receive(result); // use the result
    }
}


来源:https://stackoverflow.com/questions/12638104/await-udpclient-receiveasync-with-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!