From 43f6899ddb384902c5400a81d8232851d1068c5b Mon Sep 17 00:00:00 2001 From: "chris.watts90@outlook.com" Date: Mon, 26 Jun 2017 21:27:13 +0100 Subject: [PATCH] implement irDaemon last token caching. --- .../IrDaemonTransponderUtilities.cs | 51 +++++++++++++++++-- 1 file changed, 48 insertions(+), 3 deletions(-) diff --git a/RaceLapTimer/IrDaemonNotifier/IrDaemonTransponderUtilities.cs b/RaceLapTimer/IrDaemonNotifier/IrDaemonTransponderUtilities.cs index 64079b8..087f97c 100644 --- a/RaceLapTimer/IrDaemonNotifier/IrDaemonTransponderUtilities.cs +++ b/RaceLapTimer/IrDaemonNotifier/IrDaemonTransponderUtilities.cs @@ -1,3 +1,5 @@ +using System; +using System.Threading; using System.Threading.Tasks; using Interfaces; @@ -6,10 +8,52 @@ namespace IrDaemonNotifier public class IrDaemonTransponderUtilities : ITransponderUtilityProvider { private readonly ILoggerService _logger; + private int _lastScannedId = -1; + private readonly object _lastScanedLock = new object(); + private readonly Thread _idRefreshThread; + private bool _killRefreshThread; public IrDaemonTransponderUtilities(ILoggerService logger) { _logger = logger; + _idRefreshThread = new Thread(IrDaemonInterrogation) + { + IsBackground = true, + Name = "Ir Daemon Id Update Thread", + Priority = ThreadPriority.BelowNormal + }; + _killRefreshThread = false; + _idRefreshThread.Start(); + } + + private void IrDaemonInterrogation() + { + while (!_killRefreshThread) + { + try + { + var communicator = new IrDaemonCommunicator(_logger); + var lastId = communicator.RequestData(Commands.Properties.GetLastToken); + lock (_lastScanedLock) + { + _lastScannedId = lastId; + } + Thread.Sleep(500); + } + catch (Exception e) + { + _logger.Error(e); + } + } + } + + ~IrDaemonTransponderUtilities() + { + _killRefreshThread = true; + if (_idRefreshThread.IsAlive) + { + _idRefreshThread.Abort(); + } } public Task GetLastScannedIdAsync() @@ -24,9 +68,10 @@ namespace IrDaemonNotifier private int GetLastId() { - //TODO: implement caching here, network/request latency is mega, always exceeds 1second, this is too much - var communicator = new IrDaemonCommunicator(_logger); - return communicator.RequestData(Commands.Properties.GetLastToken); + lock (_lastScanedLock) + { + return _lastScannedId; + } } } } \ No newline at end of file