2
0

Added Lock to MemoryLogger

This commit is contained in:
glax 2023-09-02 21:53:09 +02:00
parent ad1d4dfe23
commit 6e3a9c2a78

View File

@ -6,6 +6,7 @@ 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)
{ {
@ -14,8 +15,13 @@ public class MemoryLogger : LoggerBase
protected override void Write(LogMessage value) protected override void Write(LogMessage value)
{ {
if (!_lockLogMessages)
{
_lockLogMessages = true;
while(!_logMessages.TryAdd(DateTime.Now, value)) while(!_logMessages.TryAdd(DateTime.Now, value))
Thread.Sleep(10); Thread.Sleep(10);
_lockLogMessages = false;
}
} }
public string[] GetLogMessage() public string[] GetLogMessage()
@ -35,7 +41,12 @@ public class MemoryLogger : LoggerBase
for (int retIndex = 0; retIndex < ret.Length; retIndex++) for (int retIndex = 0; retIndex < ret.Length; retIndex++)
{ {
if (!_lockLogMessages)
{
_lockLogMessages = true;
ret[retIndex] = _logMessages.GetValueAtIndex(_logMessages.Count - retLength + retIndex).ToString(); ret[retIndex] = _logMessages.GetValueAtIndex(_logMessages.Count - retLength + retIndex).ToString();
_lockLogMessages = false;
}
} }
_lastLogMessageIndex = _logMessages.Count - 1; _lastLogMessageIndex = _logMessages.Count - 1;
@ -52,7 +63,12 @@ public class MemoryLogger : LoggerBase
{ {
try try
{ {
if (!_lockLogMessages)
{
_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
{ {