From 84c5355dcfc379a7ca8d74f8229272670851d6cb Mon Sep 17 00:00:00 2001 From: Mike Phares Date: Sat, 3 Feb 2024 18:37:43 -0700 Subject: [PATCH] IsCancellationRequested --- Helpers/HelperPhysicalAddress.cs | 4 ++-- Worker.cs | 19 +++++++------------ 2 files changed, 9 insertions(+), 14 deletions(-) diff --git a/Helpers/HelperPhysicalAddress.cs b/Helpers/HelperPhysicalAddress.cs index 26fbbf6..0431709 100644 --- a/Helpers/HelperPhysicalAddress.cs +++ b/Helpers/HelperPhysicalAddress.cs @@ -128,7 +128,7 @@ internal static class HelperPhysicalAddress return keyValuePairs; } - internal static bool ParsePackets(AppSettings appSettings, ILogger logger) + internal static bool ParsePackets(AppSettings appSettings, ILogger logger, CancellationToken stoppingToken) { ILiveDevice? liveDevice = null; Version version = Pcap.SharpPcapVersion; @@ -162,7 +162,7 @@ internal static class HelperPhysicalAddress logger.LogInformation(""); liveDevice.Open(DeviceModes.Promiscuous, appSettings.PhysicalAddressConfiguration.ReadTimeoutMilliseconds); logger.LogInformation("-- Listening on {Name} {Description}", liveDevice.Name, liveDevice.Description); - while (true) + while (!stoppingToken.IsCancellationRequested) { status = liveDevice.GetNextPacket(out PacketCapture e); if (status != GetPacketStatus.PacketRead) diff --git a/Worker.cs b/Worker.cs index 8519eed..d3b0027 100644 --- a/Worker.cs +++ b/Worker.cs @@ -22,24 +22,19 @@ public partial class Worker : BackgroundService _IsWindowsService = collection.Contains(nameof(WindowsServiceLifetime)); } - private void Body() - { - _Logger.LogInformation("A) Next execute will be at {date}", DateTime.Now.AddMilliseconds(_AppSettings.MillisecondsDelay).ToString("yyyy-MM-dd hh:mm:ss.fff tt")); - _ = _AppSettings.Helper switch - { - nameof(Helpers.HelperPhysicalAddress) => Helpers.HelperPhysicalAddress.ParsePackets(_AppSettings, _Logger), - _ => throw new NotSupportedException() - }; - _Logger.LogInformation("B) Next execute will be at {date}", DateTime.Now.AddMilliseconds(_AppSettings.MillisecondsDelay).ToString("yyyy-MM-dd hh:mm:ss.fff tt")); - } - private async Task Body(CancellationToken stoppingToken) { if (!_IsWindowsService) throw new EvaluateException("Set break point and skip!"); while (_IsWindowsService && !stoppingToken.IsCancellationRequested) { - Body(); + _Logger.LogInformation("A) Next execute will be at {date}", DateTime.Now.AddMilliseconds(_AppSettings.MillisecondsDelay).ToString("yyyy-MM-dd hh:mm:ss.fff tt")); + _ = _AppSettings.Helper switch + { + nameof(Helpers.HelperPhysicalAddress) => Helpers.HelperPhysicalAddress.ParsePackets(_AppSettings, _Logger, stoppingToken), + _ => throw new NotSupportedException() + }; + _Logger.LogInformation("B) Next execute will be at {date}", DateTime.Now.AddMilliseconds(_AppSettings.MillisecondsDelay).ToString("yyyy-MM-dd hh:mm:ss.fff tt")); await Task.Delay(_AppSettings.MillisecondsDelay, stoppingToken); } }