I've built a simple app that talks over UDP, to an endpoint at an IP the user specifies. It uses System.Net.Sockets.UdpClient
, which works pretty well on Android - I'm able to send and receive packets fairly consistently. With one glaring exception... Exceptions. It seems to completely evade try/catch
; my guess is the underlying implementation errors so hard that errors cannot be caught. For example:
UdpClient Udp { get; protected set; }
Udp.Connect("192.168.1.254"); // Any bad IP
try
{
int bytesSent = await udp.SendAsync(bytes, bytes.Length);
}
catch(Exception ex)
{
return null;
}
When testing on an actual Android device, any UDP traffic sent to a bad IP consistently destroys the application.
The behavior gets crazier. For example, if I put the call out on a background thread, with a nested try/catch, like this:
Task.Run(ping).ConfigureAwait(false);
protected async Task ping()
{
try
{
await checkIp();
}
catch(Exception ex)
{
}
}
Then there are some scenarios where I actually can get an Exception - but only in the outer catch! The throw occurs on the SendAsync
call inside the inner try, but the inner catch misses it, landing only in the outer catch. The exception is a System.Net.Sockets.SocketException
with type ConnectionRefused
. Depending on how exactly I step through it, sometimes that gets caught there, sometimes not at all; when it's not at all, the app just implodes.
Is this expected behavior? Is Xamarin UdpClient just not supposed to be used? Bug? Better approach than SendAsync
? Other?