using System.Collections.Generic;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
internal static class UdpClientExtensions
{
///
/// Receives an UDP datagram if there is one in present or wait one until the timeout expires.
/// In that case a default object will be returned.
///
/// Timeout within the client needs to wait for an UDP datagram.
/// Returns the datagram if received or a default value if the timeout has expired.
public static async Task ReceiveAsync(this UdpClient client, int receiveTimeoutMilliseconds)
{
var receiveTask = client.ReceiveAsync();
if (await Task.WhenAny(receiveTask, Task.Delay(receiveTimeoutMilliseconds)) == receiveTask)
return receiveTask.Result;
return default(UdpReceiveResult);
}
///
/// Receives all the UDP datagrams coming simultaneously.
/// Stops receiving when the timeout has expired after the last datagram.
///
/// Timeout within the client needs to wait for a single datagram.
/// Returns the datagram list.
public static async Task> ReceiveAllAsync(this UdpClient client, int receiveTimeoutMilliseconds)
{
var datagramList = new List();
var read = true;
while (read)
{
var result = await client.ReceiveAsync(receiveTimeoutMilliseconds);
if (result != default(UdpReceiveResult)) datagramList.Add(result);
else read = false;
}
return datagramList;
}
}
}