From 94e34167e794e64e13baa58f21ca92cdc603f0df Mon Sep 17 00:00:00 2001
From: Richard Schneider <makaretu@gmail.com>
Date: Sun, 6 Oct 2019 09:45:21 +1300
Subject: [PATCH] fix(MulticastClient): ignore receive error.  Fixes #79

---
 src/MulticastClient.cs | 24 ++++++++++++++++++++++--
 1 file changed, 22 insertions(+), 2 deletions(-)

diff --git a/src/MulticastClient.cs b/src/MulticastClient.cs
index 4af58ac..ad20b6a 100644
--- a/src/MulticastClient.cs
+++ b/src/MulticastClient.cs
@@ -161,6 +161,8 @@ await sender.Value.SendAsync(
 
         void Listen(UdpClient receiver)
         {
+            // ReceiveAsync does not support cancellation.  So the receiver is disposed
+            // to stop it. See https://github.com/dotnet/corefx/issues/9848
             Task.Run(async () =>
             {
                 try
@@ -173,6 +175,10 @@ void Listen(UdpClient receiver)
 
                     await task.ConfigureAwait(false);
                 }
+                catch (NullReferenceException)
+                {
+                    return;
+                }
                 catch (ObjectDisposedException)
                 {
                     return;
@@ -204,7 +210,14 @@ protected virtual void Dispose(bool disposing)
 
                     foreach (var receiver in receivers)
                     {
-                        receiver.Dispose();
+                        try
+                        {
+                            receiver.Dispose();
+                        }
+                        catch
+                        {
+                            // eat it.
+                        }
                     }
                     receivers.Clear();
 
@@ -212,7 +225,14 @@ protected virtual void Dispose(bool disposing)
                     {
                         if (senders.TryRemove(address, out var sender))
                         {
-                            sender.Dispose();
+                            try
+                            {
+                                sender.Dispose();
+                            }
+                            catch
+                            {
+                                // eat it.
+                            }
                         }
                     }
                     senders.Clear();