Thread safety

This commit is contained in:
Pilzinsel64
2025-07-31 06:37:25 +02:00
parent 231546facd
commit f4530aee4f
5 changed files with 43 additions and 24 deletions

View File

@@ -8,6 +8,8 @@ public abstract class JsonDataContainer
protected readonly HashSet<object> sets = [];
public virtual HashSet<T>? Set<T>(bool allowCreate) where T : class, IDataObject
{
lock (sets)
{
var list = sets.OfType<HashSet<T>>().FirstOrDefault();
@@ -19,12 +21,16 @@ public abstract class JsonDataContainer
return list;
}
}
public virtual void CopyTo(JsonDataContainer container)
{
lock (sets)
{
foreach (var set in sets)
container.sets.Add(set);
}
}
protected virtual JsonSerializer GetSerializer()
{

View File

@@ -21,9 +21,7 @@ public class JsonDataManager(JsonDataContainer container) : DataManager
protected override void UpdateEntity<T>(T obj)
{
var set = container.Set<T>(true);
if (!set.Contains(obj))
set.Add(obj);
container.Set<T>(true).Add(obj);
}
protected override void SaveChanges()

View File

@@ -2,15 +2,23 @@
public class JsonFileContainer(string filePath) : JsonDataContainer
{
protected readonly object _lock_FileAction = new();
public override void Read()
{
lock (_lock_FileAction)
{
using var sw = new StreamReader(filePath);
GetSerializer().Populate(sw, this);
}
}
public override void Flush()
{
lock (_lock_FileAction)
{
using var sw = new StreamWriter(filePath, false);
GetSerializer().Serialize(sw, this);
}
}
}

View File

@@ -2,18 +2,25 @@
public class JsonStreamContainer(Stream stream) : JsonDataContainer
{
protected readonly object _lock_StreamAction = new();
public override void Read()
{
lock (_lock_StreamAction)
{
using var sw = new StreamReader(stream);
stream.Position = 0;
GetSerializer().Populate(sw, this);
}
}
public override void Flush()
{
lock (_lock_StreamAction)
{
using var sw = new StreamWriter(stream);
stream.Position = 0;
GetSerializer().Serialize(sw, this);
stream.SetLength(stream.Position);
}
}
}

View File

@@ -5,7 +5,7 @@
<LangVersion>latest</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>annotations</Nullable>
<Version>2.4.2</Version>
<Version>2.4.3</Version>
</PropertyGroup>
<ItemGroup>