2
0

Use lock statement instead of variable to lock logmessages

This commit is contained in:
glax 2023-09-19 15:59:52 +02:00
parent 67c23b357f
commit 88ca75e883
2 changed files with 5 additions and 13 deletions

View File

@ -1,6 +1,6 @@
namespace Logging; namespace Logging;
public class LogMessage public readonly struct LogMessage
{ {
public DateTime logTime { get; } public DateTime logTime { get; }
public string caller { get; } public string caller { get; }

View File

@ -6,7 +6,6 @@ public class MemoryLogger : LoggerBase
{ {
private readonly SortedList<DateTime, LogMessage> _logMessages = new(); private readonly SortedList<DateTime, LogMessage> _logMessages = new();
private int _lastLogMessageIndex = 0; private int _lastLogMessageIndex = 0;
private bool _lockLogMessages = false;
public MemoryLogger(Encoding? encoding = null) : base(encoding) public MemoryLogger(Encoding? encoding = null) : base(encoding)
{ {
@ -15,12 +14,9 @@ public class MemoryLogger : LoggerBase
protected override void Write(LogMessage value) protected override void Write(LogMessage value)
{ {
if (!_lockLogMessages) lock (_logMessages)
{ {
_lockLogMessages = true; _logMessages.Add(DateTime.Now, value);
while(!_logMessages.TryAdd(DateTime.Now, value))
Thread.Sleep(10);
_lockLogMessages = false;
} }
} }
@ -41,11 +37,9 @@ public class MemoryLogger : LoggerBase
for (int retIndex = 0; retIndex < ret.Length; retIndex++) for (int retIndex = 0; retIndex < ret.Length; retIndex++)
{ {
if (!_lockLogMessages) lock (_logMessages)
{ {
_lockLogMessages = true;
ret[retIndex] = _logMessages.GetValueAtIndex(_logMessages.Count - retLength + retIndex).ToString(); ret[retIndex] = _logMessages.GetValueAtIndex(_logMessages.Count - retLength + retIndex).ToString();
_lockLogMessages = false;
} }
} }
@ -63,11 +57,9 @@ public class MemoryLogger : LoggerBase
{ {
try try
{ {
if (!_lockLogMessages) lock(_logMessages)
{ {
_lockLogMessages = true;
ret.Add(_logMessages.GetValueAtIndex(_lastLogMessageIndex + retIndex).ToString()); ret.Add(_logMessages.GetValueAtIndex(_lastLogMessageIndex + retIndex).ToString());
_lockLogMessages = false;
} }
} }
catch (NullReferenceException e)//Called when LogMessage has not finished writing catch (NullReferenceException e)//Called when LogMessage has not finished writing