Skip to content

Instantly share code, notes, and snippets.

@Inok

Inok/fix.cs Secret

Created December 6, 2023 14:50
Show Gist options
  • Save Inok/666d647b1bb337bcbef8cad02032237f to your computer and use it in GitHub Desktop.
Save Inok/666d647b1bb337bcbef8cad02032237f to your computer and use it in GitHub Desktop.
Fix for UnobservedTaskException
try
{
var task = Task.Factory.FromAsync(socket.BeginConnect, socket.EndConnect, new IPEndPoint(...), null);
if (task.Wait(ConnectTimeout))
{
return socket;
}
else
{
// Timed out. Subscribe to the task to observe the exception when the task will finally complete.
_ = task.ContinueWith(x => { if (x.IsFaulted) { _ = x.Exception; } });
socket.Close();
}
}
catch
{
socket.Close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment