From 88ca75e8834e7a7d1a3754426215f35d4893e64e Mon Sep 17 00:00:00 2001 From: glax Date: Tue, 19 Sep 2023 15:59:52 +0200 Subject: [PATCH] Use lock statement instead of variable to lock logmessages --- Logging/LogMessage.cs | 2 +- Logging/MemoryLogger.cs | 16 ++++------------ 2 files changed, 5 insertions(+), 13 deletions(-) diff --git a/Logging/LogMessage.cs b/Logging/LogMessage.cs index 56515c0..ac73c44 100644 --- a/Logging/LogMessage.cs +++ b/Logging/LogMessage.cs @@ -1,6 +1,6 @@ namespace Logging; -public class LogMessage +public readonly struct LogMessage { public DateTime logTime { get; } public string caller { get; } diff --git a/Logging/MemoryLogger.cs b/Logging/MemoryLogger.cs index 5e4b92b..a612587 100644 --- a/Logging/MemoryLogger.cs +++ b/Logging/MemoryLogger.cs @@ -6,7 +6,6 @@ public class MemoryLogger : LoggerBase { private readonly SortedList _logMessages = new(); private int _lastLogMessageIndex = 0; - private bool _lockLogMessages = false; public MemoryLogger(Encoding? encoding = null) : base(encoding) { @@ -15,12 +14,9 @@ public class MemoryLogger : LoggerBase protected override void Write(LogMessage value) { - if (!_lockLogMessages) + lock (_logMessages) { - _lockLogMessages = true; - while(!_logMessages.TryAdd(DateTime.Now, value)) - Thread.Sleep(10); - _lockLogMessages = false; + _logMessages.Add(DateTime.Now, value); } } @@ -41,11 +37,9 @@ public class MemoryLogger : LoggerBase for (int retIndex = 0; retIndex < ret.Length; retIndex++) { - if (!_lockLogMessages) + lock (_logMessages) { - _lockLogMessages = true; ret[retIndex] = _logMessages.GetValueAtIndex(_logMessages.Count - retLength + retIndex).ToString(); - _lockLogMessages = false; } } @@ -63,11 +57,9 @@ public class MemoryLogger : LoggerBase { try { - if (!_lockLogMessages) + lock(_logMessages) { - _lockLogMessages = true; ret.Add(_logMessages.GetValueAtIndex(_lastLogMessageIndex + retIndex).ToString()); - _lockLogMessages = false; } } catch (NullReferenceException e)//Called when LogMessage has not finished writing