Skip to content

Commit

Permalink
feat: no threads
Browse files Browse the repository at this point in the history
  • Loading branch information
richardschneider committed May 29, 2018
1 parent 6f399c3 commit 0e42b30
Showing 1 changed file with 27 additions and 16 deletions.
43 changes: 27 additions & 16 deletions src/MulticastService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ public class MulticastService
int MulticastPort = 5353;
CancellationTokenSource listenerCancellation;
List<NetworkInterface> knownNics = new List<NetworkInterface>();
Timer nicTimer;
bool ip6;
IPEndPoint mdnsEndpoint;
// IP header (20 bytes for IPv4; 40 bytes for IPv6) and the UDP header(8 bytes).
Expand Down Expand Up @@ -141,18 +140,35 @@ public void Start()
var endpoint = new IPEndPoint(ip6 ? IPAddress.IPv6Any : IPAddress.Any, MulticastPort);
socket.Bind(endpoint);

// Start a task to find the network interface.
nicTimer = new Timer(
FindNetworkInterfaces,
this,
TimeSpan.Zero,
NetworkInterfaceDiscoveryInterval);
// Start a task to find the network interfaces.
PollNetworkInterfaces();

// Start a task to listen for MDNS messages.
Task.Run((Action)Listener, listenerCancellation.Token);
Listener();
}

void FindNetworkInterfaces(object state)
async void PollNetworkInterfaces()
{
try
{
while (true)
{
FindNetworkInterfaces();
await Task.Delay(NetworkInterfaceDiscoveryInterval, listenerCancellation.Token);
}
}
catch (TaskCanceledException)
{
// eat it
}
catch (Exception e)
{
log.Error(e);
// eat it.
}
}

void FindNetworkInterfaces()
{
var nics = NetworkInterface.GetAllNetworkInterfaces()
.Where(nic => nic.OperationalStatus == OperationalStatus.Up)
Expand All @@ -164,7 +180,7 @@ void FindNetworkInterfaces(object state)
{
lock (socketLock)
{
if (socket == null || nicTimer == null)
if (socket == null)
return;

IPInterfaceProperties properties = nic.GetIPProperties();
Expand Down Expand Up @@ -197,7 +213,7 @@ void FindNetworkInterfaces(object state)
{
lock (socketLock)
{
if (socket == null || nicTimer == null)
if (socket == null)
return;
NetworkInterfaceDiscovered?.Invoke(this, new NetworkInterfaceEventArgs
{
Expand All @@ -218,11 +234,6 @@ public void Stop()
QueryReceived = null;
AnswerReceived = null;
NetworkInterfaceDiscovered = null;
if (nicTimer != null)
{
nicTimer.Dispose();
nicTimer = null;
}
if (listenerCancellation != null)
{
listenerCancellation.Cancel();
Expand Down

0 comments on commit 0e42b30

Please sign in to comment.