fixed code formatter.
minor bug fixes to a few systems as well.
This commit is contained in:
parent
657e19f48f
commit
01d2cbf4b3
@ -27,19 +27,19 @@ namespace AdvChkSys
|
||||
/// <summary>
|
||||
/// Creates a new WorldConstraints object.
|
||||
/// </summary>
|
||||
public static WorldConstraints CreateDefaultConstraints() => new WorldConstraints();
|
||||
public static WorldConstraints CreateDefaultConstraints() => new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new 2D chunk manager with optional constraints.
|
||||
/// </summary>
|
||||
public static ChunkManager2D<byte> Create2DManager(WorldConstraints? constraints = null) =>
|
||||
new ChunkManager2D<byte>(constraints);
|
||||
new(constraints);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new 3D chunk manager with optional constraints.
|
||||
/// </summary>
|
||||
public static ChunkManager3D<byte> Create3DManager(WorldConstraints? constraints = null) =>
|
||||
new ChunkManager3D<byte>(constraints);
|
||||
new(constraints);
|
||||
|
||||
/// <summary>
|
||||
/// Gets a detailed report of the current memory usage by the chunk system.
|
||||
@ -51,7 +51,7 @@ namespace AdvChkSys
|
||||
/// Logs the current memory usage to the provided logging action.
|
||||
/// </summary>
|
||||
/// <param name="logAction">Action that will receive the log messages</param>
|
||||
public static void LogMemoryUsage(Action<string> logAction) =>
|
||||
public static void LogMemoryUsage(Action<string> logAction) =>
|
||||
MemoryUsageReporter.LogMemoryUsage(logAction);
|
||||
|
||||
/// <summary>
|
||||
@ -62,7 +62,7 @@ namespace AdvChkSys
|
||||
/// <summary>
|
||||
/// Runs a batch of chunk operations in parallel.
|
||||
/// </summary>
|
||||
public static Task RunParallelChunkOperationsAsync(IEnumerable<Action> operations,
|
||||
public static Task RunParallelChunkOperationsAsync(IEnumerable<Action> operations,
|
||||
int? maxDegreeOfParallelism = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
@ -73,13 +73,13 @@ namespace AdvChkSys
|
||||
/// Creates a spatial index for 2D chunks.
|
||||
/// </summary>
|
||||
public static SpatialChunkIndex<Chunk2D<T>> CreateSpatialIndex2D<T>() =>
|
||||
new SpatialChunkIndex<Chunk2D<T>>();
|
||||
new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a spatial index for 3D chunks.
|
||||
/// </summary>
|
||||
public static SpatialChunkIndex<Chunk3D<T>> CreateSpatialIndex3D<T>() =>
|
||||
new SpatialChunkIndex<Chunk3D<T>>();
|
||||
new();
|
||||
|
||||
/// <summary>
|
||||
/// Configures the threading system for high throughput.
|
||||
@ -155,7 +155,7 @@ namespace AdvChkSys
|
||||
manager2D.UnloadChunk(1, 1);
|
||||
manager3D.UnloadChunk(1, 1, 1);
|
||||
|
||||
return resourceTracking2D && resourceTracking3D && constraintsWork &&
|
||||
return resourceTracking2D && resourceTracking3D && constraintsWork &&
|
||||
spatialIndexWorks && threadingWorks;
|
||||
}
|
||||
}
|
||||
|
||||
@ -91,13 +91,13 @@ namespace AdvChkSys.Chunk
|
||||
get
|
||||
{
|
||||
if (localX < 0 || localX >= Width || localY < 0 || localY >= Height)
|
||||
throw new ArgumentOutOfRangeException($"Coordinates ({localX}, {localY}) out of bounds [0-{Width-1}, 0-{Height-1}]");
|
||||
throw new ArgumentOutOfRangeException($"Coordinates ({localX}, {localY}) out of bounds [0-{Width - 1}, 0-{Height - 1}]");
|
||||
return _isAllAir ? default! : _data![localX, localY];
|
||||
}
|
||||
set
|
||||
{
|
||||
if (localX < 0 || localX >= Width || localY < 0 || localY >= Height)
|
||||
throw new ArgumentOutOfRangeException($"Coordinates ({localX}, {localY}) out of bounds [0-{Width-1}, 0-{Height-1}]");
|
||||
throw new ArgumentOutOfRangeException($"Coordinates ({localX}, {localY}) out of bounds [0-{Width - 1}, 0-{Height - 1}]");
|
||||
if (_isAllAir)
|
||||
throw new InvalidOperationException("Cannot set cell in all-air chunk.");
|
||||
_data![localX, localY] = value;
|
||||
|
||||
@ -6,210 +6,210 @@ using AdvChkSys.Interfaces;
|
||||
|
||||
namespace AdvChkSys.Chunk
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a 3D chunk of data in the world.
|
||||
/// Perspective-agnostic and supports arbitrary data types and metadata.
|
||||
/// </summary>
|
||||
public class Chunk3D<T> : IChunk, IDisposable
|
||||
{
|
||||
// Array pool for chunk data arrays
|
||||
private static readonly ConcurrentBag<T[,,]> _arrayPool = new();
|
||||
|
||||
// Flyweight: one all-air instance per size
|
||||
private static readonly Dictionary<(int, int, int), Chunk3D<T>> _allAirChunks = new();
|
||||
|
||||
/// <summary>
|
||||
/// Represents a 3D chunk of data in the world.
|
||||
/// Perspective-agnostic and supports arbitrary data types and metadata.
|
||||
/// Returns a singleton all-air chunk for the given size and position.
|
||||
/// </summary>
|
||||
public class Chunk3D<T> : IChunk, IDisposable
|
||||
public static Chunk3D<T> AllAir(int x, int y, int z, int width, int height, int depth)
|
||||
{
|
||||
// Array pool for chunk data arrays
|
||||
private static readonly ConcurrentBag<T[,,]> _arrayPool = new();
|
||||
|
||||
// Flyweight: one all-air instance per size
|
||||
private static readonly Dictionary<(int, int, int), Chunk3D<T>> _allAirChunks = new();
|
||||
|
||||
/// <summary>
|
||||
/// Returns a singleton all-air chunk for the given size and position.
|
||||
/// </summary>
|
||||
public static Chunk3D<T> AllAir(int x, int y, int z, int width, int height, int depth)
|
||||
var key = (width, height, depth);
|
||||
if (!_allAirChunks.TryGetValue(key, out var chunk))
|
||||
{
|
||||
var key = (width, height, depth);
|
||||
if (!_allAirChunks.TryGetValue(key, out var chunk))
|
||||
{
|
||||
chunk = new Chunk3D<T>(x, y, z, width, height, depth, isAllAir: true);
|
||||
_allAirChunks[key] = chunk;
|
||||
}
|
||||
chunk.SetPosition(x, y, z); // Use explicit method for position update
|
||||
return chunk;
|
||||
chunk = new Chunk3D<T>(x, y, z, width, height, depth, isAllAir: true);
|
||||
_allAirChunks[key] = chunk;
|
||||
}
|
||||
chunk.SetPosition(x, y, z); // Use explicit method for position update
|
||||
return chunk;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The chunk's X position in chunk coordinates.
|
||||
/// </summary>
|
||||
public int X { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// The chunk's Y position in chunk coordinates.
|
||||
/// </summary>
|
||||
public int Y { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// The chunk's Z position in chunk coordinates.
|
||||
/// </summary>
|
||||
public int Z { get; private set; }
|
||||
/// <summary>
|
||||
/// The chunk's X position in chunk coordinates.
|
||||
/// </summary>
|
||||
public int X { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// The width of the chunk in cells.
|
||||
/// </summary>
|
||||
public int Width { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The height of the chunk in cells.
|
||||
/// </summary>
|
||||
public int Height { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The depth of the chunk in cells.
|
||||
/// </summary>
|
||||
public int Depth { get; }
|
||||
/// <summary>
|
||||
/// The chunk's Y position in chunk coordinates.
|
||||
/// </summary>
|
||||
public int Y { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// The chunk's data array.
|
||||
/// </summary>
|
||||
private readonly T[,,]? _data;
|
||||
/// <summary>
|
||||
/// The chunk's Z position in chunk coordinates.
|
||||
/// </summary>
|
||||
public int Z { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Metadata dictionary for arbitrary chunk information (e.g., biome, tags).
|
||||
/// </summary>
|
||||
public Dictionary<string, object> Metadata { get; }
|
||||
/// <summary>
|
||||
/// The width of the chunk in cells.
|
||||
/// </summary>
|
||||
public int Width { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if this chunk is the all-air singleton.
|
||||
/// </summary>
|
||||
public bool IsAllAir { get; private set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// Tracks whether the chunk has been disposed.
|
||||
/// </summary>
|
||||
private bool _disposed;
|
||||
/// <summary>
|
||||
/// The height of the chunk in cells.
|
||||
/// </summary>
|
||||
public int Height { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new 3D chunk at the specified position with the given dimensions.
|
||||
/// </summary>
|
||||
/// <param name="x">X coordinate in chunk space</param>
|
||||
/// <param name="y">Y coordinate in chunk space</param>
|
||||
/// <param name="z">Z coordinate in chunk space</param>
|
||||
/// <param name="width">Width of the chunk in cells</param>
|
||||
/// <param name="height">Height of the chunk in cells</param>
|
||||
/// <param name="depth">Depth of the chunk in cells</param>
|
||||
public Chunk3D(int x, int y, int z, int width, int height, int depth)
|
||||
: this(x, y, z, width, height, depth, false)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new 3D chunk at the specified position with the given dimensions.
|
||||
/// </summary>
|
||||
/// <param name="x">X coordinate in chunk space</param>
|
||||
/// <param name="y">Y coordinate in chunk space</param>
|
||||
/// <param name="z">Z coordinate in chunk space</param>
|
||||
/// <param name="width">Width of the chunk in cells</param>
|
||||
/// <param name="height">Height of the chunk in cells</param>
|
||||
/// <param name="depth">Depth of the chunk in cells</param>
|
||||
/// <param name="isAllAir">Whether this is an all-air chunk</param>
|
||||
public Chunk3D(int x, int y, int z, int width, int height, int depth, bool isAllAir = false)
|
||||
{
|
||||
X = x;
|
||||
Y = y;
|
||||
Z = z;
|
||||
Width = width;
|
||||
Height = height;
|
||||
Depth = depth;
|
||||
IsAllAir = isAllAir;
|
||||
_data = isAllAir ? null : RentArray(width, height, depth);
|
||||
Metadata = new Dictionary<string, object>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Explicitly sets the chunk's position. Used internally for all-air singleton.
|
||||
/// </summary>
|
||||
internal void SetPosition(int x, int y, int z)
|
||||
{
|
||||
X = x;
|
||||
Y = y;
|
||||
Z = z;
|
||||
}
|
||||
/// <summary>
|
||||
/// The depth of the chunk in cells.
|
||||
/// </summary>
|
||||
public int Depth { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the value at the given local chunk coordinates.
|
||||
/// </summary>
|
||||
public T this[int localX, int localY, int localZ]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (IsAllAir)
|
||||
return default!;
|
||||
return _data![localX, localY, localZ];
|
||||
}
|
||||
set
|
||||
{
|
||||
if (IsAllAir)
|
||||
throw new InvalidOperationException("Cannot modify an all-air chunk.");
|
||||
_data![localX, localY, localZ] = value;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// The chunk's data array.
|
||||
/// </summary>
|
||||
private readonly T[,,]? _data;
|
||||
|
||||
/// <summary>
|
||||
/// Fills the chunk with a specified value.
|
||||
/// </summary>
|
||||
public void Fill(T value)
|
||||
/// <summary>
|
||||
/// Metadata dictionary for arbitrary chunk information (e.g., biome, tags).
|
||||
/// </summary>
|
||||
public Dictionary<string, object> Metadata { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if this chunk is the all-air singleton.
|
||||
/// </summary>
|
||||
public bool IsAllAir { get; private set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// Tracks whether the chunk has been disposed.
|
||||
/// </summary>
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new 3D chunk at the specified position with the given dimensions.
|
||||
/// </summary>
|
||||
/// <param name="x">X coordinate in chunk space</param>
|
||||
/// <param name="y">Y coordinate in chunk space</param>
|
||||
/// <param name="z">Z coordinate in chunk space</param>
|
||||
/// <param name="width">Width of the chunk in cells</param>
|
||||
/// <param name="height">Height of the chunk in cells</param>
|
||||
/// <param name="depth">Depth of the chunk in cells</param>
|
||||
public Chunk3D(int x, int y, int z, int width, int height, int depth)
|
||||
: this(x, y, z, width, height, depth, false)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new 3D chunk at the specified position with the given dimensions.
|
||||
/// </summary>
|
||||
/// <param name="x">X coordinate in chunk space</param>
|
||||
/// <param name="y">Y coordinate in chunk space</param>
|
||||
/// <param name="z">Z coordinate in chunk space</param>
|
||||
/// <param name="width">Width of the chunk in cells</param>
|
||||
/// <param name="height">Height of the chunk in cells</param>
|
||||
/// <param name="depth">Depth of the chunk in cells</param>
|
||||
/// <param name="isAllAir">Whether this is an all-air chunk</param>
|
||||
public Chunk3D(int x, int y, int z, int width, int height, int depth, bool isAllAir = false)
|
||||
{
|
||||
X = x;
|
||||
Y = y;
|
||||
Z = z;
|
||||
Width = width;
|
||||
Height = height;
|
||||
Depth = depth;
|
||||
IsAllAir = isAllAir;
|
||||
_data = isAllAir ? null : RentArray(width, height, depth);
|
||||
Metadata = new Dictionary<string, object>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Explicitly sets the chunk's position. Used internally for all-air singleton.
|
||||
/// </summary>
|
||||
internal void SetPosition(int x, int y, int z)
|
||||
{
|
||||
X = x;
|
||||
Y = y;
|
||||
Z = z;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the value at the given local chunk coordinates.
|
||||
/// </summary>
|
||||
public T this[int localX, int localY, int localZ]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (IsAllAir)
|
||||
throw new InvalidOperationException("Cannot fill an all-air chunk.");
|
||||
|
||||
for (int x = 0; x < Width; x++)
|
||||
for (int y = 0; y < Height; y++)
|
||||
for (int z = 0; z < Depth; z++)
|
||||
_data![x, y, z] = value;
|
||||
return default!;
|
||||
return _data![localX, localY, localZ];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rents an array from the pool or creates a new one.
|
||||
/// </summary>
|
||||
private static T[,,] RentArray(int width, int height, int depth)
|
||||
set
|
||||
{
|
||||
if (_arrayPool.TryTake(out var arr) &&
|
||||
arr.GetLength(0) == width &&
|
||||
arr.GetLength(1) == height &&
|
||||
arr.GetLength(2) == depth)
|
||||
return arr;
|
||||
return new T[width, height, depth];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns an array to the pool.
|
||||
/// </summary>
|
||||
internal static void ReturnArray(T[,,] arr)
|
||||
{
|
||||
_arrayPool.Add(arr);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the underlying data array (for pooling).
|
||||
/// </summary>
|
||||
internal T[,,]? GetDataArray() => _data;
|
||||
|
||||
/// <summary>
|
||||
/// Releases the data array back to the pool.
|
||||
/// </summary>
|
||||
internal void ReleaseDataArray()
|
||||
{
|
||||
if (_data != null && !IsAllAir)
|
||||
{
|
||||
ReturnArray(_data);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the chunk and returns its resources to the pool.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
ReleaseDataArray();
|
||||
_disposed = true;
|
||||
}
|
||||
if (IsAllAir)
|
||||
throw new InvalidOperationException("Cannot modify an all-air chunk.");
|
||||
_data![localX, localY, localZ] = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fills the chunk with a specified value.
|
||||
/// </summary>
|
||||
public void Fill(T value)
|
||||
{
|
||||
if (IsAllAir)
|
||||
throw new InvalidOperationException("Cannot fill an all-air chunk.");
|
||||
|
||||
for (int x = 0; x < Width; x++)
|
||||
for (int y = 0; y < Height; y++)
|
||||
for (int z = 0; z < Depth; z++)
|
||||
_data![x, y, z] = value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rents an array from the pool or creates a new one.
|
||||
/// </summary>
|
||||
private static T[,,] RentArray(int width, int height, int depth)
|
||||
{
|
||||
if (_arrayPool.TryTake(out var arr) &&
|
||||
arr.GetLength(0) == width &&
|
||||
arr.GetLength(1) == height &&
|
||||
arr.GetLength(2) == depth)
|
||||
return arr;
|
||||
return new T[width, height, depth];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns an array to the pool.
|
||||
/// </summary>
|
||||
internal static void ReturnArray(T[,,] arr)
|
||||
{
|
||||
_arrayPool.Add(arr);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the underlying data array (for pooling).
|
||||
/// </summary>
|
||||
internal T[,,]? GetDataArray() => _data;
|
||||
|
||||
/// <summary>
|
||||
/// Releases the data array back to the pool.
|
||||
/// </summary>
|
||||
internal void ReleaseDataArray()
|
||||
{
|
||||
if (_data != null && !IsAllAir)
|
||||
{
|
||||
ReturnArray(_data);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the chunk and returns its resources to the pool.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
ReleaseDataArray();
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,67 +1,67 @@
|
||||
using System;
|
||||
|
||||
namespace AdvChkSys.Constraints
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents constraints and limits for the chunk world.
|
||||
/// Can be used to restrict world size, chunk counts, and other resource limits.
|
||||
/// </summary>
|
||||
public class WorldConstraints
|
||||
{
|
||||
/// <summary>
|
||||
/// If set, the minimum allowed chunk X coordinate (inclusive).
|
||||
/// Represents constraints and limits for the chunk world.
|
||||
/// Can be used to restrict world size, chunk counts, and other resource limits.
|
||||
/// </summary>
|
||||
public int? MinChunkX { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// If set, the maximum allowed chunk X coordinate (inclusive).
|
||||
/// </summary>
|
||||
public int? MaxChunkX { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// If set, the minimum allowed chunk Y coordinate (inclusive).
|
||||
/// </summary>
|
||||
public int? MinChunkY { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// If set, the maximum allowed chunk Y coordinate (inclusive).
|
||||
/// </summary>
|
||||
public int? MaxChunkY { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// If set, the minimum allowed chunk Z coordinate (inclusive).
|
||||
/// </summary>
|
||||
public int? MinChunkZ { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// If set, the maximum allowed chunk Z coordinate (inclusive).
|
||||
/// </summary>
|
||||
public int? MaxChunkZ { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// If set, the maximum number of chunks allowed to be loaded in memory at once.
|
||||
/// </summary>
|
||||
public int? MaxLoadedChunks { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the given chunk coordinates are within the allowed world bounds.
|
||||
/// </summary>
|
||||
public bool IsWithinBounds(int chunkX, int chunkY)
|
||||
public class WorldConstraints
|
||||
{
|
||||
if (MinChunkX.HasValue && chunkX < MinChunkX.Value) return false;
|
||||
if (MaxChunkX.HasValue && chunkX > MaxChunkX.Value) return false;
|
||||
if (MinChunkY.HasValue && chunkY < MinChunkY.Value) return false;
|
||||
if (MaxChunkY.HasValue && chunkY > MaxChunkY.Value) return false;
|
||||
return true;
|
||||
}
|
||||
/// <summary>
|
||||
/// If set, the minimum allowed chunk X coordinate (inclusive).
|
||||
/// </summary>
|
||||
public int? MinChunkX { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the current number of loaded chunks is within the allowed limit.
|
||||
/// </summary>
|
||||
public bool IsWithinChunkLimit(int loadedChunkCount)
|
||||
{
|
||||
if (MaxLoadedChunks.HasValue && loadedChunkCount > MaxLoadedChunks.Value) return false;
|
||||
return true;
|
||||
/// <summary>
|
||||
/// If set, the maximum allowed chunk X coordinate (inclusive).
|
||||
/// </summary>
|
||||
public int? MaxChunkX { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// If set, the minimum allowed chunk Y coordinate (inclusive).
|
||||
/// </summary>
|
||||
public int? MinChunkY { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// If set, the maximum allowed chunk Y coordinate (inclusive).
|
||||
/// </summary>
|
||||
public int? MaxChunkY { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// If set, the minimum allowed chunk Z coordinate (inclusive).
|
||||
/// </summary>
|
||||
public int? MinChunkZ { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// If set, the maximum allowed chunk Z coordinate (inclusive).
|
||||
/// </summary>
|
||||
public int? MaxChunkZ { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// If set, the maximum number of chunks allowed to be loaded in memory at once.
|
||||
/// </summary>
|
||||
public int? MaxLoadedChunks { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the given chunk coordinates are within the allowed world bounds.
|
||||
/// </summary>
|
||||
public bool IsWithinBounds(int chunkX, int chunkY)
|
||||
{
|
||||
if (MinChunkX.HasValue && chunkX < MinChunkX.Value) return false;
|
||||
if (MaxChunkX.HasValue && chunkX > MaxChunkX.Value) return false;
|
||||
if (MinChunkY.HasValue && chunkY < MinChunkY.Value) return false;
|
||||
if (MaxChunkY.HasValue && chunkY > MaxChunkY.Value) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the current number of loaded chunks is within the allowed limit.
|
||||
/// </summary>
|
||||
public bool IsWithinChunkLimit(int loadedChunkCount)
|
||||
{
|
||||
if (MaxLoadedChunks.HasValue && loadedChunkCount > MaxLoadedChunks.Value) return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -29,7 +29,7 @@ namespace AdvChkSys.Diagnostics
|
||||
|
||||
// Calculate estimated chunk memory usage
|
||||
report.EstimatedChunkMemoryBytes = EstimateChunkMemoryUsage(report.ActiveChunkCount);
|
||||
|
||||
|
||||
return report;
|
||||
}
|
||||
|
||||
@ -51,14 +51,16 @@ namespace AdvChkSys.Diagnostics
|
||||
{
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
|
||||
{
|
||||
var memStatus = new MemoryHelper.MEMORYSTATUSEX();
|
||||
memStatus.dwLength = (uint)Marshal.SizeOf(typeof(MemoryHelper.MEMORYSTATUSEX));
|
||||
var memStatus = new MemoryHelper.MEMORYSTATUSEX
|
||||
{
|
||||
dwLength = (uint)Marshal.SizeOf(typeof(MemoryHelper.MEMORYSTATUSEX))
|
||||
};
|
||||
if (MemoryHelper.GlobalMemoryStatusEx(ref memStatus))
|
||||
{
|
||||
return memStatus.ullTotalPhys;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// For non-Windows platforms or if Windows call fails, use a fallback
|
||||
return 8UL * 1024 * 1024 * 1024; // Assume 8GB as fallback
|
||||
}
|
||||
@ -70,7 +72,7 @@ namespace AdvChkSys.Diagnostics
|
||||
public static void LogMemoryUsage(Action<string> logAction)
|
||||
{
|
||||
var report = GetMemoryUsage();
|
||||
|
||||
|
||||
logAction($"--- AdvChkSys Memory Report ({report.Timestamp:yyyy-MM-dd HH:mm:ss}) ---");
|
||||
logAction($"Active Chunks: {report.ActiveChunkCount:N0}");
|
||||
logAction($"Estimated Chunk Memory: {FormatByteSize(report.EstimatedChunkMemoryBytes)}");
|
||||
@ -88,7 +90,7 @@ namespace AdvChkSys.Diagnostics
|
||||
string[] sizes = { "B", "KB", "MB", "GB", "TB" };
|
||||
double formattedSize = bytes;
|
||||
int order = 0;
|
||||
|
||||
|
||||
while (formattedSize >= 1024 && order < sizes.Length - 1)
|
||||
{
|
||||
order++;
|
||||
@ -132,9 +134,9 @@ namespace AdvChkSys.Diagnostics
|
||||
/// <summary>
|
||||
/// Percentage of total system memory used by chunks.
|
||||
/// </summary>
|
||||
public double MemoryUsagePercentage =>
|
||||
TotalSystemMemoryBytes > 0
|
||||
? (double)EstimatedChunkMemoryBytes / TotalSystemMemoryBytes * 100
|
||||
public double MemoryUsagePercentage =>
|
||||
TotalSystemMemoryBytes > 0
|
||||
? (double)EstimatedChunkMemoryBytes / TotalSystemMemoryBytes * 100
|
||||
: 0;
|
||||
}
|
||||
}
|
||||
@ -4,123 +4,123 @@ using System.Threading;
|
||||
|
||||
namespace AdvChkSys.Events
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides events for chunk lifecycle operations such as loading, unloading, saving, and more.
|
||||
/// Thread-safe event subscription and invocation.
|
||||
/// </summary>
|
||||
public static class ChunkEvents
|
||||
{
|
||||
// Backing fields for thread-safe event handling
|
||||
private static Action<Interfaces.IChunk>? _chunkLoaded;
|
||||
private static Action<Interfaces.IChunk>? _chunkUnloaded;
|
||||
private static Action<Interfaces.IChunk>? _chunkLoading;
|
||||
private static Action<Interfaces.IChunk>? _chunkUnloading;
|
||||
private static Action<Interfaces.IChunk>? _chunkSaving;
|
||||
private static Action<Interfaces.IChunk>? _chunkSaved;
|
||||
|
||||
/// <summary>
|
||||
/// Occurs when a chunk has been loaded into memory.
|
||||
/// Provides events for chunk lifecycle operations such as loading, unloading, saving, and more.
|
||||
/// Thread-safe event subscription and invocation.
|
||||
/// </summary>
|
||||
public static event Action<Interfaces.IChunk> ChunkLoaded
|
||||
public static class ChunkEvents
|
||||
{
|
||||
add => AddHandler(ref _chunkLoaded, value);
|
||||
remove => RemoveHandler(ref _chunkLoaded, value);
|
||||
}
|
||||
// Backing fields for thread-safe event handling
|
||||
private static Action<Interfaces.IChunk>? _chunkLoaded;
|
||||
private static Action<Interfaces.IChunk>? _chunkUnloaded;
|
||||
private static Action<Interfaces.IChunk>? _chunkLoading;
|
||||
private static Action<Interfaces.IChunk>? _chunkUnloading;
|
||||
private static Action<Interfaces.IChunk>? _chunkSaving;
|
||||
private static Action<Interfaces.IChunk>? _chunkSaved;
|
||||
|
||||
/// <summary>
|
||||
/// Occurs when a chunk is about to be loaded into memory.
|
||||
/// </summary>
|
||||
public static event Action<Interfaces.IChunk> ChunkLoading
|
||||
{
|
||||
add => AddHandler(ref _chunkLoading, value);
|
||||
remove => RemoveHandler(ref _chunkLoading, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Occurs when a chunk is about to be unloaded from memory.
|
||||
/// </summary>
|
||||
public static event Action<Interfaces.IChunk> ChunkUnloading
|
||||
{
|
||||
add => AddHandler(ref _chunkUnloading, value);
|
||||
remove => RemoveHandler(ref _chunkUnloading, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Occurs when a chunk has been unloaded from memory.
|
||||
/// </summary>
|
||||
public static event Action<Interfaces.IChunk> ChunkUnloaded
|
||||
{
|
||||
add => AddHandler(ref _chunkUnloaded, value);
|
||||
remove => RemoveHandler(ref _chunkUnloaded, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Occurs when a chunk is about to be saved.
|
||||
/// </summary>
|
||||
public static event Action<Interfaces.IChunk> ChunkSaving
|
||||
{
|
||||
add => AddHandler(ref _chunkSaving, value);
|
||||
remove => RemoveHandler(ref _chunkSaving, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Occurs when a chunk has been saved.
|
||||
/// </summary>
|
||||
public static event Action<Interfaces.IChunk> ChunkSaved
|
||||
{
|
||||
add => AddHandler(ref _chunkSaved, value);
|
||||
remove => RemoveHandler(ref _chunkSaved, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raises the ChunkLoading event.
|
||||
/// </summary>
|
||||
public static void OnChunkLoading(Interfaces.IChunk chunk) => _chunkLoading?.Invoke(chunk);
|
||||
|
||||
/// <summary>
|
||||
/// Raises the ChunkLoaded event.
|
||||
/// </summary>
|
||||
public static void OnChunkLoaded(Interfaces.IChunk chunk) => _chunkLoaded?.Invoke(chunk);
|
||||
|
||||
/// <summary>
|
||||
/// Raises the ChunkUnloading event.
|
||||
/// </summary>
|
||||
public static void OnChunkUnloading(Interfaces.IChunk chunk) => _chunkUnloading?.Invoke(chunk);
|
||||
|
||||
/// <summary>
|
||||
/// Raises the ChunkUnloaded event.
|
||||
/// </summary>
|
||||
public static void OnChunkUnloaded(Interfaces.IChunk chunk) => _chunkUnloaded?.Invoke(chunk);
|
||||
|
||||
/// <summary>
|
||||
/// Raises the ChunkSaving event.
|
||||
/// </summary>
|
||||
public static void OnChunkSaving(Interfaces.IChunk chunk) => _chunkSaving?.Invoke(chunk);
|
||||
|
||||
/// <summary>
|
||||
/// Raises the ChunkSaved event.
|
||||
/// </summary>
|
||||
public static void OnChunkSaved(Interfaces.IChunk chunk) => _chunkSaved?.Invoke(chunk);
|
||||
|
||||
// Thread-safe add/remove for event handlers
|
||||
private static void AddHandler(ref Action<Interfaces.IChunk>? field, Action<Interfaces.IChunk> handler)
|
||||
{
|
||||
Action<Interfaces.IChunk>? prevHandler, newHandler;
|
||||
do
|
||||
/// <summary>
|
||||
/// Occurs when a chunk has been loaded into memory.
|
||||
/// </summary>
|
||||
public static event Action<Interfaces.IChunk> ChunkLoaded
|
||||
{
|
||||
prevHandler = field;
|
||||
newHandler = (Action<Interfaces.IChunk>?)Delegate.Combine(prevHandler, handler);
|
||||
} while (Interlocked.CompareExchange(ref field, newHandler, prevHandler) != prevHandler);
|
||||
}
|
||||
add => AddHandler(ref _chunkLoaded, value);
|
||||
remove => RemoveHandler(ref _chunkLoaded, value);
|
||||
}
|
||||
|
||||
private static void RemoveHandler(ref Action<Interfaces.IChunk>? field, Action<Interfaces.IChunk> handler)
|
||||
{
|
||||
Action<Interfaces.IChunk>? prevHandler, newHandler;
|
||||
do
|
||||
/// <summary>
|
||||
/// Occurs when a chunk is about to be loaded into memory.
|
||||
/// </summary>
|
||||
public static event Action<Interfaces.IChunk> ChunkLoading
|
||||
{
|
||||
prevHandler = field;
|
||||
newHandler = (Action<Interfaces.IChunk>?)Delegate.Remove(prevHandler, handler);
|
||||
} while (Interlocked.CompareExchange(ref field, newHandler, prevHandler) != prevHandler);
|
||||
add => AddHandler(ref _chunkLoading, value);
|
||||
remove => RemoveHandler(ref _chunkLoading, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Occurs when a chunk is about to be unloaded from memory.
|
||||
/// </summary>
|
||||
public static event Action<Interfaces.IChunk> ChunkUnloading
|
||||
{
|
||||
add => AddHandler(ref _chunkUnloading, value);
|
||||
remove => RemoveHandler(ref _chunkUnloading, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Occurs when a chunk has been unloaded from memory.
|
||||
/// </summary>
|
||||
public static event Action<Interfaces.IChunk> ChunkUnloaded
|
||||
{
|
||||
add => AddHandler(ref _chunkUnloaded, value);
|
||||
remove => RemoveHandler(ref _chunkUnloaded, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Occurs when a chunk is about to be saved.
|
||||
/// </summary>
|
||||
public static event Action<Interfaces.IChunk> ChunkSaving
|
||||
{
|
||||
add => AddHandler(ref _chunkSaving, value);
|
||||
remove => RemoveHandler(ref _chunkSaving, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Occurs when a chunk has been saved.
|
||||
/// </summary>
|
||||
public static event Action<Interfaces.IChunk> ChunkSaved
|
||||
{
|
||||
add => AddHandler(ref _chunkSaved, value);
|
||||
remove => RemoveHandler(ref _chunkSaved, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raises the ChunkLoading event.
|
||||
/// </summary>
|
||||
public static void OnChunkLoading(Interfaces.IChunk chunk) => _chunkLoading?.Invoke(chunk);
|
||||
|
||||
/// <summary>
|
||||
/// Raises the ChunkLoaded event.
|
||||
/// </summary>
|
||||
public static void OnChunkLoaded(Interfaces.IChunk chunk) => _chunkLoaded?.Invoke(chunk);
|
||||
|
||||
/// <summary>
|
||||
/// Raises the ChunkUnloading event.
|
||||
/// </summary>
|
||||
public static void OnChunkUnloading(Interfaces.IChunk chunk) => _chunkUnloading?.Invoke(chunk);
|
||||
|
||||
/// <summary>
|
||||
/// Raises the ChunkUnloaded event.
|
||||
/// </summary>
|
||||
public static void OnChunkUnloaded(Interfaces.IChunk chunk) => _chunkUnloaded?.Invoke(chunk);
|
||||
|
||||
/// <summary>
|
||||
/// Raises the ChunkSaving event.
|
||||
/// </summary>
|
||||
public static void OnChunkSaving(Interfaces.IChunk chunk) => _chunkSaving?.Invoke(chunk);
|
||||
|
||||
/// <summary>
|
||||
/// Raises the ChunkSaved event.
|
||||
/// </summary>
|
||||
public static void OnChunkSaved(Interfaces.IChunk chunk) => _chunkSaved?.Invoke(chunk);
|
||||
|
||||
// Thread-safe add/remove for event handlers
|
||||
private static void AddHandler(ref Action<Interfaces.IChunk>? field, Action<Interfaces.IChunk> handler)
|
||||
{
|
||||
Action<Interfaces.IChunk>? prevHandler, newHandler;
|
||||
do
|
||||
{
|
||||
prevHandler = field;
|
||||
newHandler = (Action<Interfaces.IChunk>?)Delegate.Combine(prevHandler, handler);
|
||||
} while (Interlocked.CompareExchange(ref field, newHandler, prevHandler) != prevHandler);
|
||||
}
|
||||
|
||||
private static void RemoveHandler(ref Action<Interfaces.IChunk>? field, Action<Interfaces.IChunk> handler)
|
||||
{
|
||||
Action<Interfaces.IChunk>? prevHandler, newHandler;
|
||||
do
|
||||
{
|
||||
prevHandler = field;
|
||||
newHandler = (Action<Interfaces.IChunk>?)Delegate.Remove(prevHandler, handler);
|
||||
} while (Interlocked.CompareExchange(ref field, newHandler, prevHandler) != prevHandler);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -12,7 +12,7 @@ namespace AdvChkSys.Interfaces
|
||||
/// The chunk's X position in chunk-space coordinates.
|
||||
/// </summary>
|
||||
int X { get; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// The chunk's Y position in chunk-space coordinates.
|
||||
/// </summary>
|
||||
|
||||
@ -2,37 +2,37 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace AdvChkSys.Interfaces
|
||||
{
|
||||
/// <summary>
|
||||
/// Interface for managing chunks in memory.
|
||||
/// Provides methods for loading, unloading, and accessing chunks.
|
||||
/// </summary>
|
||||
public interface IChunkManager
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns true if the chunk at (x, y) is loaded.
|
||||
/// Interface for managing chunks in memory.
|
||||
/// Provides methods for loading, unloading, and accessing chunks.
|
||||
/// </summary>
|
||||
bool IsChunkLoaded(int x, int y);
|
||||
public interface IChunkManager
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns true if the chunk at (x, y) is loaded.
|
||||
/// </summary>
|
||||
bool IsChunkLoaded(int x, int y);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the chunk at (x, y) if loaded, or null if not.
|
||||
/// </summary>
|
||||
IChunk? GetChunk(int x, int y);
|
||||
/// <summary>
|
||||
/// Gets the chunk at (x, y) if loaded, or null if not.
|
||||
/// </summary>
|
||||
IChunk? GetChunk(int x, int y);
|
||||
|
||||
/// <summary>
|
||||
/// Loads or creates a chunk at (x, y) with the given size.
|
||||
/// Returns the loaded or newly created chunk.
|
||||
/// </summary>
|
||||
IChunk LoadOrCreateChunk(int x, int y, int width, int height);
|
||||
/// <summary>
|
||||
/// Loads or creates a chunk at (x, y) with the given size.
|
||||
/// Returns the loaded or newly created chunk.
|
||||
/// </summary>
|
||||
IChunk LoadOrCreateChunk(int x, int y, int width, int height);
|
||||
|
||||
/// <summary>
|
||||
/// Unloads (removes) the chunk at (x, y) if loaded.
|
||||
/// </summary>
|
||||
bool UnloadChunk(int x, int y);
|
||||
/// <summary>
|
||||
/// Unloads (removes) the chunk at (x, y) if loaded.
|
||||
/// </summary>
|
||||
bool UnloadChunk(int x, int y);
|
||||
|
||||
/// <summary>
|
||||
/// Enumerates all loaded chunks.
|
||||
/// </summary>
|
||||
IEnumerable<IChunk> GetAllChunks();
|
||||
}
|
||||
/// <summary>
|
||||
/// Enumerates all loaded chunks.
|
||||
/// </summary>
|
||||
IEnumerable<IChunk> GetAllChunks();
|
||||
}
|
||||
}
|
||||
@ -20,23 +20,23 @@ namespace AdvChkSys.Manager
|
||||
private readonly WorldConstraints? _constraints;
|
||||
private readonly int _capacity;
|
||||
private readonly Dictionary<(int, int), Task<Chunk2D<T>>> _loadingChunks = new();
|
||||
private readonly object _lock = new object();
|
||||
private readonly object _lock = new();
|
||||
|
||||
/// <summary>
|
||||
/// Delegate for custom air check logic
|
||||
/// </summary>
|
||||
private Func<int, int, int, int, bool>? _airCheckDelegate;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// World generator for determining empty regions
|
||||
/// </summary>
|
||||
private IWorldGenerator? _worldGenerator;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Data provider for determining empty regions
|
||||
/// </summary>
|
||||
private IDataProvider? _dataProvider;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Height map for determining sky chunks
|
||||
/// </summary>
|
||||
@ -155,7 +155,7 @@ namespace AdvChkSys.Manager
|
||||
{
|
||||
var key = (x, y);
|
||||
Task<Chunk2D<T>>? task = null;
|
||||
|
||||
|
||||
// First check if we already have a task
|
||||
lock (_lock)
|
||||
{
|
||||
@ -173,7 +173,7 @@ namespace AdvChkSys.Manager
|
||||
|
||||
// Otherwise, create a new task outside the lock
|
||||
task = Task.Run(() => LoadOrCreateChunk(x, y, width, height));
|
||||
|
||||
|
||||
// Register the task
|
||||
lock (_lock)
|
||||
{
|
||||
@ -244,7 +244,7 @@ namespace AdvChkSys.Manager
|
||||
IChunk IChunkManager.LoadOrCreateChunk(int x, int y, int width, int height) => LoadOrCreateChunk(x, y, width, height);
|
||||
bool IChunkManager.UnloadChunk(int x, int y) => UnloadChunk(x, y);
|
||||
IEnumerable<IChunk> IChunkManager.GetAllChunks() => _chunks.Values;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Sets a custom delegate for determining if a region should be all air.
|
||||
/// </summary>
|
||||
@ -252,7 +252,7 @@ namespace AdvChkSys.Manager
|
||||
{
|
||||
_airCheckDelegate = airCheckDelegate;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Sets a world generator for determining empty regions.
|
||||
/// </summary>
|
||||
@ -260,7 +260,7 @@ namespace AdvChkSys.Manager
|
||||
{
|
||||
_worldGenerator = worldGenerator;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Sets a data provider for determining empty regions.
|
||||
/// </summary>
|
||||
@ -268,7 +268,7 @@ namespace AdvChkSys.Manager
|
||||
{
|
||||
_dataProvider = dataProvider;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Sets a height map for determining sky chunks.
|
||||
/// </summary>
|
||||
@ -277,7 +277,7 @@ namespace AdvChkSys.Manager
|
||||
_heightMap = heightMap;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Interface for world generators that can determine if regions are empty.
|
||||
/// </summary>
|
||||
@ -288,7 +288,7 @@ namespace AdvChkSys.Manager
|
||||
/// </summary>
|
||||
bool IsRegionEmpty(int x, int y, int width, int height);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Interface for data providers that can determine if regions are empty.
|
||||
/// </summary>
|
||||
@ -299,7 +299,7 @@ namespace AdvChkSys.Manager
|
||||
/// </summary>
|
||||
bool IsEmptyRegion(int x, int y, int width, int height);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Interface for height maps that can determine the maximum height at a position.
|
||||
/// </summary>
|
||||
|
||||
@ -21,7 +21,7 @@ namespace AdvChkSys.Manager
|
||||
private readonly LRUCache<(int, int, int), Chunk3D<T>> _chunks;
|
||||
private readonly WorldConstraints? _constraints;
|
||||
private readonly int _capacity;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Delegate for custom air check logic
|
||||
/// </summary>
|
||||
@ -67,7 +67,7 @@ namespace AdvChkSys.Manager
|
||||
_chunks.TryGet((x, y, z), out var chunk);
|
||||
return chunk;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Determines if a region should be represented as an all-air chunk.
|
||||
/// </summary>
|
||||
@ -139,7 +139,7 @@ namespace AdvChkSys.Manager
|
||||
arr = arrField.GetValue(chunk) as T[,,];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (!chunk.IsAllAir && arr != null)
|
||||
{
|
||||
Chunk3D<T>.ReturnArray(arr);
|
||||
@ -175,7 +175,7 @@ namespace AdvChkSys.Manager
|
||||
LoadOrCreateChunk(x, y, 0, width, height, 1);
|
||||
bool IChunkManager.UnloadChunk(int x, int y) => UnloadChunk(x, y, 0);
|
||||
IEnumerable<IChunk> IChunkManager.GetAllChunks() => _chunks.Values;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Sets a custom delegate for determining if a region should be all air.
|
||||
/// </summary>
|
||||
@ -208,7 +208,7 @@ namespace AdvChkSys.Manager
|
||||
_heightMap = heightMap;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Interface for 3D world generators that can determine if regions are empty.
|
||||
/// </summary>
|
||||
|
||||
@ -6,67 +6,67 @@ using System.Collections.Generic;
|
||||
|
||||
namespace AdvChkSys.Resources
|
||||
{
|
||||
/// <summary>
|
||||
/// Manages allocation and release of chunk resources in memory.
|
||||
/// Can be extended to track resource usage, pooling, or implement custom memory strategies.
|
||||
/// </summary>
|
||||
public static class ChunkResourceManager
|
||||
{
|
||||
// Example: Track allocated chunks (for diagnostics, pooling, or resource limits)
|
||||
private static readonly ConcurrentDictionary<IChunk, DateTime> _allocatedChunks = new ConcurrentDictionary<IChunk, DateTime>();
|
||||
private static int _allocatedChunkCount;
|
||||
private static readonly object _lock = new object();
|
||||
private static readonly HashSet<IChunk> _activeChunks = new();
|
||||
|
||||
/// <summary>
|
||||
/// Called when a chunk is allocated/loaded into memory.
|
||||
/// Tracks the chunk and can be extended for pooling or resource limits.
|
||||
/// Manages allocation and release of chunk resources in memory.
|
||||
/// Can be extended to track resource usage, pooling, or implement custom memory strategies.
|
||||
/// </summary>
|
||||
public static void AllocateChunk(IChunk chunk)
|
||||
public static class ChunkResourceManager
|
||||
{
|
||||
lock (_lock)
|
||||
// Example: Track allocated chunks (for diagnostics, pooling, or resource limits)
|
||||
private static readonly ConcurrentDictionary<IChunk, DateTime> _allocatedChunks = new();
|
||||
private static int _allocatedChunkCount;
|
||||
private static readonly object _lock = new();
|
||||
private static readonly HashSet<IChunk> _activeChunks = new();
|
||||
|
||||
/// <summary>
|
||||
/// Called when a chunk is allocated/loaded into memory.
|
||||
/// Tracks the chunk and can be extended for pooling or resource limits.
|
||||
/// </summary>
|
||||
public static void AllocateChunk(IChunk chunk)
|
||||
{
|
||||
_allocatedChunkCount++;
|
||||
_activeChunks.Add(chunk);
|
||||
lock (_lock)
|
||||
{
|
||||
_allocatedChunkCount++;
|
||||
_activeChunks.Add(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called when a chunk is released/unloaded from memory.
|
||||
/// Removes the chunk from tracking and can be extended for pooling or cleanup.
|
||||
/// </summary>
|
||||
public static void ReleaseChunk(IChunk chunk)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_allocatedChunkCount--;
|
||||
_activeChunks.Remove(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current number of allocated chunks.
|
||||
/// </summary>
|
||||
public static int AllocatedChunkCount => _allocatedChunks.Count;
|
||||
|
||||
/// <summary>
|
||||
/// Clears all tracked chunks (for diagnostics or shutdown).
|
||||
/// </summary>
|
||||
public static void Clear()
|
||||
{
|
||||
_allocatedChunks.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current count of active chunks being tracked by the resource manager.
|
||||
/// </summary>
|
||||
/// <returns>The number of active chunks</returns>
|
||||
public static int GetActiveChunkCount()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _activeChunks.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called when a chunk is released/unloaded from memory.
|
||||
/// Removes the chunk from tracking and can be extended for pooling or cleanup.
|
||||
/// </summary>
|
||||
public static void ReleaseChunk(IChunk chunk)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_allocatedChunkCount--;
|
||||
_activeChunks.Remove(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current number of allocated chunks.
|
||||
/// </summary>
|
||||
public static int AllocatedChunkCount => _allocatedChunks.Count;
|
||||
|
||||
/// <summary>
|
||||
/// Clears all tracked chunks (for diagnostics or shutdown).
|
||||
/// </summary>
|
||||
public static void Clear()
|
||||
{
|
||||
_allocatedChunks.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current count of active chunks being tracked by the resource manager.
|
||||
/// </summary>
|
||||
/// <returns>The number of active chunks</returns>
|
||||
public static int GetActiveChunkCount()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _activeChunks.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -15,19 +15,19 @@ namespace AdvChkSys.Spatial
|
||||
{
|
||||
return new Chunk3DAdapter<T>(chunk);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Adapter to make Chunk3D implement IChunk3D.
|
||||
/// </summary>
|
||||
private class Chunk3DAdapter<T> : IChunk3D
|
||||
{
|
||||
private readonly Chunk3D<T> _chunk;
|
||||
|
||||
|
||||
public Chunk3DAdapter(Chunk3D<T> chunk)
|
||||
{
|
||||
_chunk = chunk;
|
||||
}
|
||||
|
||||
|
||||
public int X => _chunk.X;
|
||||
public int Y => _chunk.Y;
|
||||
public int Z => _chunk.Z;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -13,16 +13,16 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
// Lock objects for each chunk
|
||||
private readonly ConcurrentDictionary<IChunk, SemaphoreSlim> _locks = new();
|
||||
|
||||
|
||||
// Timer for cleanup
|
||||
private readonly Timer _cleanupTimer;
|
||||
|
||||
|
||||
// Last access time for each lock
|
||||
private readonly ConcurrentDictionary<IChunk, DateTime> _lastAccessTime = new();
|
||||
|
||||
|
||||
// Cleanup interval in minutes
|
||||
private readonly int _cleanupIntervalMinutes;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the ChunkAsyncLock class.
|
||||
/// </summary>
|
||||
@ -30,11 +30,11 @@ namespace AdvChkSys.Threading
|
||||
public ChunkAsyncLock(int cleanupIntervalMinutes = 10)
|
||||
{
|
||||
_cleanupIntervalMinutes = cleanupIntervalMinutes;
|
||||
_cleanupTimer = new Timer(CleanupUnusedLocks, null,
|
||||
TimeSpan.FromMinutes(cleanupIntervalMinutes),
|
||||
_cleanupTimer = new Timer(CleanupUnusedLocks, null,
|
||||
TimeSpan.FromMinutes(cleanupIntervalMinutes),
|
||||
TimeSpan.FromMinutes(cleanupIntervalMinutes));
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Acquires a lock on a chunk asynchronously.
|
||||
/// </summary>
|
||||
@ -45,7 +45,7 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
var semaphore = _locks.GetOrAdd(chunk, _ => new SemaphoreSlim(1, 1));
|
||||
_lastAccessTime[chunk] = DateTime.UtcNow;
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
@ -60,13 +60,13 @@ namespace AdvChkSys.Threading
|
||||
_lastAccessTime.TryRemove(chunk, out _);
|
||||
semaphore.Dispose();
|
||||
}
|
||||
|
||||
|
||||
throw;
|
||||
}
|
||||
|
||||
|
||||
return new LockReleaser(semaphore, chunk, this);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Tries to acquire a lock on a chunk asynchronously with a timeout.
|
||||
/// </summary>
|
||||
@ -75,24 +75,24 @@ namespace AdvChkSys.Threading
|
||||
/// <param name="cancellationToken">Cancellation token</param>
|
||||
/// <returns>A tuple with a boolean indicating success and the lock releaser if successful</returns>
|
||||
public async Task<(bool Success, IDisposable? LockReleaser)> TryLockAsync(
|
||||
IChunk chunk,
|
||||
TimeSpan timeout,
|
||||
IChunk chunk,
|
||||
TimeSpan timeout,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (chunk == null)
|
||||
throw new ArgumentNullException(nameof(chunk));
|
||||
|
||||
|
||||
var semaphore = _locks.GetOrAdd(chunk, _ => new SemaphoreSlim(1, 1));
|
||||
_lastAccessTime[chunk] = DateTime.UtcNow;
|
||||
|
||||
|
||||
if (await semaphore.WaitAsync(timeout, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
return (true, new LockReleaser(semaphore, chunk, this));
|
||||
}
|
||||
|
||||
|
||||
return (false, null);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Cleans up unused locks.
|
||||
/// </summary>
|
||||
@ -100,10 +100,10 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
var threshold = now.AddMinutes(-_cleanupIntervalMinutes);
|
||||
|
||||
|
||||
foreach (var chunk in _lastAccessTime.Keys)
|
||||
{
|
||||
if (_lastAccessTime.TryGetValue(chunk, out var lastAccess) &&
|
||||
if (_lastAccessTime.TryGetValue(chunk, out var lastAccess) &&
|
||||
lastAccess < threshold &&
|
||||
_locks.TryGetValue(chunk, out var semaphore))
|
||||
{
|
||||
@ -119,23 +119,23 @@ namespace AdvChkSys.Threading
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Disposes resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_cleanupTimer.Dispose();
|
||||
|
||||
|
||||
foreach (var semaphore in _locks.Values)
|
||||
{
|
||||
semaphore.Dispose();
|
||||
}
|
||||
|
||||
|
||||
_locks.Clear();
|
||||
_lastAccessTime.Clear();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Releases a lock when disposed.
|
||||
/// </summary>
|
||||
@ -145,14 +145,14 @@ namespace AdvChkSys.Threading
|
||||
private readonly IChunk _chunk;
|
||||
private readonly ChunkAsyncLock _parent;
|
||||
private bool _disposed;
|
||||
|
||||
|
||||
public LockReleaser(SemaphoreSlim semaphore, IChunk chunk, ChunkAsyncLock parent)
|
||||
{
|
||||
_semaphore = semaphore;
|
||||
_chunk = chunk;
|
||||
_parent = parent;
|
||||
}
|
||||
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (!_disposed)
|
||||
|
||||
@ -14,16 +14,16 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
// Queue of pending operations for each chunk
|
||||
private readonly ConcurrentDictionary<IChunk, Queue<(Func<Task> Operation, TaskCompletionSource<object?> Completion)>> _pendingOperations = new();
|
||||
|
||||
|
||||
// Currently active operations
|
||||
private readonly ConcurrentDictionary<IChunk, Task> _activeOperations = new();
|
||||
|
||||
|
||||
// Semaphore to limit concurrent operations
|
||||
private readonly SemaphoreSlim _semaphore;
|
||||
|
||||
|
||||
// Cancellation for shutdown
|
||||
private readonly CancellationTokenSource _shutdownCts = new();
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the ChunkOperationQueue class.
|
||||
/// </summary>
|
||||
@ -32,7 +32,7 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
_semaphore = new SemaphoreSlim(maxConcurrentOperations, maxConcurrentOperations);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Enqueues an operation to be performed on a chunk.
|
||||
/// </summary>
|
||||
@ -43,31 +43,31 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
if (chunk == null)
|
||||
throw new ArgumentNullException(nameof(chunk));
|
||||
|
||||
|
||||
if (operation == null)
|
||||
throw new ArgumentNullException(nameof(operation));
|
||||
|
||||
|
||||
// Create a completion source for this operation
|
||||
var completion = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
|
||||
// Get or create the queue for this chunk
|
||||
var queue = _pendingOperations.GetOrAdd(chunk, _ => new Queue<(Func<Task>, TaskCompletionSource<object?>)>());
|
||||
|
||||
|
||||
// Add the operation to the queue
|
||||
lock (queue)
|
||||
{
|
||||
queue.Enqueue((operation, completion));
|
||||
|
||||
|
||||
// If this is the only operation, start processing
|
||||
if (queue.Count == 1 && !_activeOperations.ContainsKey(chunk))
|
||||
{
|
||||
StartProcessingChunkOperations(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return completion.Task;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Starts processing operations for a chunk.
|
||||
/// </summary>
|
||||
@ -75,7 +75,7 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
// Wait for a semaphore slot
|
||||
await _semaphore.WaitAsync(_shutdownCts.Token).ConfigureAwait(false);
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
// Process operations until the queue is empty
|
||||
@ -83,9 +83,9 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
// Get the next operation
|
||||
(Func<Task> operation, TaskCompletionSource<object?> completion) nextOperation;
|
||||
|
||||
|
||||
var queue = _pendingOperations.GetOrAdd(chunk, _ => new Queue<(Func<Task>, TaskCompletionSource<object?>)>());
|
||||
|
||||
|
||||
lock (queue)
|
||||
{
|
||||
if (queue.Count == 0)
|
||||
@ -94,17 +94,17 @@ namespace AdvChkSys.Threading
|
||||
_activeOperations.TryRemove(chunk, out _);
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
nextOperation = queue.Peek();
|
||||
}
|
||||
|
||||
|
||||
// Execute the operation
|
||||
var task = ExecuteOperationAsync(chunk, nextOperation.operation, nextOperation.completion);
|
||||
_activeOperations[chunk] = task;
|
||||
|
||||
|
||||
// Wait for completion
|
||||
await task.ConfigureAwait(false);
|
||||
|
||||
|
||||
// Remove the completed operation
|
||||
lock (queue)
|
||||
{
|
||||
@ -132,12 +132,12 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
// Track the operation for diagnostics
|
||||
var operationId = ChunkThreadingDiagnostics.TrackOperationStart("ChunkOperation", chunk);
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
// Execute the operation
|
||||
await operation().ConfigureAwait(false);
|
||||
|
||||
|
||||
// Complete the task
|
||||
completion.TrySetResult(null);
|
||||
}
|
||||
@ -145,7 +145,7 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
// Set the exception
|
||||
completion.TrySetException(ex);
|
||||
|
||||
|
||||
// Log the error
|
||||
ChunkThreadingDiagnostics.LogEvent("OperationError", $"Error in chunk operation: {ex.Message}");
|
||||
}
|
||||
@ -159,7 +159,7 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
// This should never happen, but just in case
|
||||
completion.TrySetException(ex);
|
||||
|
||||
|
||||
// Log the error
|
||||
ChunkThreadingDiagnostics.LogEvent("CriticalError", $"Critical error in operation execution: {ex.Message}");
|
||||
}
|
||||
@ -177,7 +177,7 @@ namespace AdvChkSys.Threading
|
||||
return queue.Count;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@ -217,18 +217,18 @@ namespace AdvChkSys.Threading
|
||||
lock (queue)
|
||||
{
|
||||
int count = queue.Count;
|
||||
|
||||
|
||||
// Cancel all pending operations
|
||||
while (queue.Count > 0)
|
||||
{
|
||||
var operation = queue.Dequeue();
|
||||
operation.Completion.TrySetCanceled();
|
||||
var (Operation, Completion) = queue.Dequeue();
|
||||
Completion.TrySetCanceled();
|
||||
}
|
||||
|
||||
|
||||
return count;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@ -239,12 +239,12 @@ namespace AdvChkSys.Threading
|
||||
public int CancelAllOperations()
|
||||
{
|
||||
int count = 0;
|
||||
|
||||
|
||||
foreach (var chunk in _pendingOperations.Keys)
|
||||
{
|
||||
count += CancelOperations(chunk);
|
||||
}
|
||||
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
@ -255,17 +255,17 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
// Cancel all operations
|
||||
_shutdownCts.Cancel();
|
||||
|
||||
|
||||
// Cancel all pending operations
|
||||
CancelAllOperations();
|
||||
|
||||
|
||||
// Wait for active operations to complete
|
||||
var tasks = new List<Task>(_activeOperations.Values);
|
||||
if (tasks.Count > 0)
|
||||
{
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
// Dispose resources
|
||||
_shutdownCts.Dispose();
|
||||
_semaphore.Dispose();
|
||||
|
||||
@ -30,7 +30,7 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
// Build dependency graph
|
||||
var dependencyGraph = BuildDependencyGraph(chunks, getDependencies);
|
||||
|
||||
|
||||
// Process in dependency order
|
||||
await ProcessDependencyGraphAsync(
|
||||
dependencyGraph,
|
||||
@ -38,7 +38,7 @@ namespace AdvChkSys.Threading
|
||||
maxDegreeOfParallelism,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Builds a dependency graph for chunks.
|
||||
/// </summary>
|
||||
@ -47,13 +47,13 @@ namespace AdvChkSys.Threading
|
||||
Func<IChunk, IEnumerable<IChunk>> getDependencies)
|
||||
{
|
||||
var graph = new DependencyGraph();
|
||||
|
||||
|
||||
// Add all chunks to the graph
|
||||
foreach (var chunk in chunks)
|
||||
{
|
||||
graph.AddNode(chunk);
|
||||
}
|
||||
|
||||
|
||||
// Add dependencies
|
||||
foreach (var chunk in chunks)
|
||||
{
|
||||
@ -63,10 +63,10 @@ namespace AdvChkSys.Threading
|
||||
graph.AddDependency(chunk, dependency);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return graph;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Processes a dependency graph in parallel.
|
||||
/// </summary>
|
||||
@ -79,28 +79,28 @@ namespace AdvChkSys.Threading
|
||||
// Set up semaphore for parallelism control
|
||||
var semaphore = new SemaphoreSlim(
|
||||
maxDegreeOfParallelism ?? ChunkThreadingConfiguration.DefaultMaxDegreeOfParallelism);
|
||||
|
||||
|
||||
// Track completed chunks
|
||||
var completed = new ConcurrentDictionary<IChunk, bool>();
|
||||
|
||||
|
||||
// Get initial set of chunks with no dependencies
|
||||
var readyChunks = new ConcurrentQueue<IChunk>(graph.GetNodesWithNoDependencies());
|
||||
|
||||
|
||||
// Track active tasks
|
||||
var activeTasks = new ConcurrentDictionary<IChunk, Task>();
|
||||
|
||||
|
||||
// Process until all chunks are completed
|
||||
while (!readyChunks.IsEmpty || activeTasks.Count > 0)
|
||||
{
|
||||
// Check for cancellation
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
|
||||
// Start processing ready chunks
|
||||
while (readyChunks.TryDequeue(out var chunk))
|
||||
{
|
||||
// Wait for a semaphore slot
|
||||
await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
|
||||
// Start processing this chunk
|
||||
var task = ProcessChunkAsync(
|
||||
chunk,
|
||||
@ -110,27 +110,27 @@ namespace AdvChkSys.Threading
|
||||
readyChunks,
|
||||
semaphore,
|
||||
cancellationToken);
|
||||
|
||||
|
||||
activeTasks[chunk] = task;
|
||||
|
||||
|
||||
// When the task completes, remove it from active tasks
|
||||
_ = task.ContinueWith(_ =>
|
||||
_ = task.ContinueWith(_ =>
|
||||
{
|
||||
activeTasks.TryRemove(chunk, out _);
|
||||
}, TaskContinuationOptions.ExecuteSynchronously);
|
||||
}
|
||||
|
||||
|
||||
// If no ready chunks but active tasks, wait for one to complete
|
||||
if (readyChunks.IsEmpty && activeTasks.Count > 0)
|
||||
{
|
||||
await Task.WhenAny(activeTasks.Values).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Clean up
|
||||
semaphore.Dispose();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Processes a single chunk and updates the ready queue.
|
||||
/// </summary>
|
||||
@ -147,10 +147,10 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
// Process the chunk
|
||||
await processor(chunk).ConfigureAwait(false);
|
||||
|
||||
|
||||
// Mark as completed
|
||||
completed[chunk] = true;
|
||||
|
||||
|
||||
// Find dependents that are now ready
|
||||
var dependents = graph.GetDependents(chunk);
|
||||
foreach (var dependent in dependents)
|
||||
@ -170,7 +170,7 @@ namespace AdvChkSys.Threading
|
||||
semaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Represents a dependency graph for chunks.
|
||||
/// </summary>
|
||||
@ -178,10 +178,10 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
// Map of chunk to its dependencies
|
||||
private readonly Dictionary<IChunk, HashSet<IChunk>> _dependencies = new();
|
||||
|
||||
|
||||
// Map of chunk to chunks that depend on it
|
||||
private readonly Dictionary<IChunk, HashSet<IChunk>> _dependents = new();
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Adds a node to the graph.
|
||||
/// </summary>
|
||||
@ -191,13 +191,13 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
_dependencies[chunk] = new HashSet<IChunk>();
|
||||
}
|
||||
|
||||
|
||||
if (!_dependents.ContainsKey(chunk))
|
||||
{
|
||||
_dependents[chunk] = new HashSet<IChunk>();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Adds a dependency between two nodes.
|
||||
/// </summary>
|
||||
@ -206,14 +206,14 @@ namespace AdvChkSys.Threading
|
||||
// Add nodes if they don't exist
|
||||
AddNode(dependent);
|
||||
AddNode(dependency);
|
||||
|
||||
|
||||
// Add dependency
|
||||
_dependencies[dependent].Add(dependency);
|
||||
|
||||
|
||||
// Add dependent
|
||||
_dependents[dependency].Add(dependent);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets all nodes with no dependencies.
|
||||
/// </summary>
|
||||
@ -221,7 +221,7 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
return _dependencies.Where(kvp => kvp.Value.Count == 0).Select(kvp => kvp.Key);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets all dependencies of a node.
|
||||
/// </summary>
|
||||
@ -231,10 +231,10 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
return dependencies;
|
||||
}
|
||||
|
||||
|
||||
return Enumerable.Empty<IChunk>();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets all dependents of a node.
|
||||
/// </summary>
|
||||
@ -244,7 +244,7 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
return dependents;
|
||||
}
|
||||
|
||||
|
||||
return Enumerable.Empty<IChunk>();
|
||||
}
|
||||
}
|
||||
|
||||
@ -92,18 +92,18 @@ namespace AdvChkSys.Threading
|
||||
using var timeoutCts = new CancellationTokenSource(timeout);
|
||||
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
|
||||
timeoutCts.Token, cancellationToken);
|
||||
|
||||
|
||||
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, linkedCts.Token))
|
||||
.ConfigureAwait(false);
|
||||
|
||||
|
||||
if (completedTask == task)
|
||||
{
|
||||
return await task.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
throw new TimeoutException($"The operation timed out after {timeout.TotalMilliseconds}ms");
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Runs a task with a timeout.
|
||||
/// </summary>
|
||||
@ -119,19 +119,19 @@ namespace AdvChkSys.Threading
|
||||
using var timeoutCts = new CancellationTokenSource(timeout);
|
||||
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
|
||||
timeoutCts.Token, cancellationToken);
|
||||
|
||||
|
||||
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, linkedCts.Token))
|
||||
.ConfigureAwait(false);
|
||||
|
||||
|
||||
if (completedTask == task)
|
||||
{
|
||||
await task.ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
throw new TimeoutException($"The operation timed out after {timeout.TotalMilliseconds}ms");
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Runs a task with a fallback value if it times out.
|
||||
/// </summary>
|
||||
@ -156,25 +156,25 @@ namespace AdvChkSys.Threading
|
||||
return fallbackValue;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Runs multiple actions in parallel with a limit on the degree of parallelism.
|
||||
/// </summary>
|
||||
public static Task RunBatchParallelAsync(IEnumerable<Action> actions, int? maxDegreeOfParallelism = null,
|
||||
public static Task RunBatchParallelAsync(IEnumerable<Action> actions, int? maxDegreeOfParallelism = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
return Task.Run(() =>
|
||||
return Task.Run(() =>
|
||||
{
|
||||
var options = new ParallelOptions
|
||||
{
|
||||
MaxDegreeOfParallelism = maxDegreeOfParallelism ?? MaxDegreeOfParallelism,
|
||||
CancellationToken = cancellationToken
|
||||
};
|
||||
|
||||
|
||||
Parallel.ForEach(actions, options, action => action());
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Runs a batch of functions in parallel and returns the results.
|
||||
/// </summary>
|
||||
@ -190,24 +190,24 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
var funcs = functions.ToArray();
|
||||
var results = new T[funcs.Length];
|
||||
|
||||
await Task.Run(() =>
|
||||
|
||||
await Task.Run(() =>
|
||||
{
|
||||
var options = new ParallelOptions
|
||||
{
|
||||
MaxDegreeOfParallelism = maxDegreeOfParallelism ?? MaxDegreeOfParallelism,
|
||||
CancellationToken = cancellationToken
|
||||
};
|
||||
|
||||
Parallel.For(0, funcs.Length, options, i =>
|
||||
|
||||
Parallel.For(0, funcs.Length, options, i =>
|
||||
{
|
||||
results[i] = funcs[i]();
|
||||
});
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Runs a batch of async functions in parallel.
|
||||
/// </summary>
|
||||
@ -220,24 +220,24 @@ namespace AdvChkSys.Threading
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var funcs = functions.ToArray();
|
||||
|
||||
|
||||
if (funcs.Length == 0)
|
||||
return;
|
||||
|
||||
|
||||
// Use SemaphoreSlim to limit concurrency
|
||||
using var semaphore = new SemaphoreSlim(
|
||||
maxDegreeOfParallelism ?? MaxDegreeOfParallelism);
|
||||
|
||||
|
||||
// Create tasks for all functions
|
||||
var tasks = new List<Task>(funcs.Length);
|
||||
|
||||
|
||||
foreach (var func in funcs)
|
||||
{
|
||||
// Wait for a slot in the semaphore
|
||||
await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
|
||||
// Create a task that releases the semaphore when done
|
||||
var task = Task.Run(async () =>
|
||||
var task = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
@ -248,14 +248,14 @@ namespace AdvChkSys.Threading
|
||||
semaphore.Release();
|
||||
}
|
||||
}, cancellationToken);
|
||||
|
||||
|
||||
tasks.Add(task);
|
||||
}
|
||||
|
||||
|
||||
// Wait for all tasks to complete
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Runs a batch of async functions in parallel and returns the results.
|
||||
/// </summary>
|
||||
@ -270,27 +270,27 @@ namespace AdvChkSys.Threading
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var funcs = functions.ToArray();
|
||||
|
||||
|
||||
if (funcs.Length == 0)
|
||||
return Array.Empty<T>();
|
||||
|
||||
|
||||
// Use SemaphoreSlim to limit concurrency
|
||||
using var semaphore = new SemaphoreSlim(
|
||||
maxDegreeOfParallelism ?? MaxDegreeOfParallelism);
|
||||
|
||||
|
||||
// Create tasks for all functions
|
||||
var tasks = new Task<T>[funcs.Length];
|
||||
|
||||
|
||||
for (int i = 0; i < funcs.Length; i++)
|
||||
{
|
||||
var func = funcs[i];
|
||||
var index = i;
|
||||
|
||||
|
||||
// Wait for a slot in the semaphore
|
||||
await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
|
||||
// Create a task that releases the semaphore when done
|
||||
tasks[index] = Task.Run(async () =>
|
||||
tasks[index] = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
@ -302,7 +302,7 @@ namespace AdvChkSys.Threading
|
||||
}
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
|
||||
// Wait for all tasks to complete
|
||||
return await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@ -14,7 +14,7 @@ namespace AdvChkSys.Threading
|
||||
/// Maximum degree of parallelism for chunk operations.
|
||||
/// </summary>
|
||||
public static int MaxDegreeOfParallelism { get; set; } = Environment.ProcessorCount;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Runs a batch of actions in parallel.
|
||||
/// </summary>
|
||||
@ -29,7 +29,7 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
if (actions == null || actions.Length == 0)
|
||||
return Task.CompletedTask;
|
||||
|
||||
|
||||
return Task.Run(() =>
|
||||
{
|
||||
var options = new ParallelOptions
|
||||
@ -37,11 +37,11 @@ namespace AdvChkSys.Threading
|
||||
MaxDegreeOfParallelism = maxDegreeOfParallelism ?? MaxDegreeOfParallelism,
|
||||
CancellationToken = cancellationToken
|
||||
};
|
||||
|
||||
|
||||
Parallel.ForEach(actions, options, action => action());
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Creates a cancellation token with a timeout.
|
||||
/// </summary>
|
||||
@ -54,7 +54,7 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
if (timeout == TimeSpan.MaxValue)
|
||||
return cancellationToken;
|
||||
|
||||
|
||||
var source = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
source.CancelAfter(timeout);
|
||||
return source.Token;
|
||||
|
||||
@ -12,16 +12,16 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
// Lock objects for each chunk
|
||||
private readonly ConcurrentDictionary<IChunk, ChunkLock> _locks = new();
|
||||
|
||||
|
||||
// Timer for cleanup
|
||||
private readonly Timer _cleanupTimer;
|
||||
|
||||
|
||||
// Last access time for each lock
|
||||
private readonly ConcurrentDictionary<IChunk, DateTime> _lastAccessTime = new();
|
||||
|
||||
|
||||
// Cleanup interval in minutes
|
||||
private readonly int _cleanupIntervalMinutes;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the ChunkThreadSafetyManager class.
|
||||
/// </summary>
|
||||
@ -29,11 +29,11 @@ namespace AdvChkSys.Threading
|
||||
public ChunkThreadSafetyManager(int cleanupIntervalMinutes = 10)
|
||||
{
|
||||
_cleanupIntervalMinutes = cleanupIntervalMinutes;
|
||||
_cleanupTimer = new Timer(CleanupUnusedLocks, null,
|
||||
TimeSpan.FromMinutes(cleanupIntervalMinutes),
|
||||
_cleanupTimer = new Timer(CleanupUnusedLocks, null,
|
||||
TimeSpan.FromMinutes(cleanupIntervalMinutes),
|
||||
TimeSpan.FromMinutes(cleanupIntervalMinutes));
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Acquires an exclusive lock on a chunk.
|
||||
/// </summary>
|
||||
@ -43,12 +43,12 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
var lockObj = _locks.GetOrAdd(chunk, _ => new ChunkLock());
|
||||
_lastAccessTime[chunk] = DateTime.UtcNow;
|
||||
|
||||
|
||||
lockObj.EnterWriteLock();
|
||||
|
||||
|
||||
return new LockReleaser(lockObj, chunk, this, LockType.Write);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Acquires a read lock on a chunk.
|
||||
/// </summary>
|
||||
@ -58,12 +58,12 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
var lockObj = _locks.GetOrAdd(chunk, _ => new ChunkLock());
|
||||
_lastAccessTime[chunk] = DateTime.UtcNow;
|
||||
|
||||
|
||||
lockObj.EnterReadLock();
|
||||
|
||||
|
||||
return new LockReleaser(lockObj, chunk, this, LockType.Read);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Acquires a write lock on a chunk.
|
||||
/// </summary>
|
||||
@ -73,12 +73,12 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
var lockObj = _locks.GetOrAdd(chunk, _ => new ChunkLock());
|
||||
_lastAccessTime[chunk] = DateTime.UtcNow;
|
||||
|
||||
|
||||
lockObj.EnterWriteLock();
|
||||
|
||||
|
||||
return new LockReleaser(lockObj, chunk, this, LockType.Write);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Tries to acquire a read lock on a chunk.
|
||||
/// </summary>
|
||||
@ -89,18 +89,18 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
var lockObj = _locks.GetOrAdd(chunk, _ => new ChunkLock());
|
||||
_lastAccessTime[chunk] = DateTime.UtcNow;
|
||||
|
||||
|
||||
if (lockObj.TryEnterReadLock(timeout))
|
||||
{
|
||||
return new LockReleaser(lockObj, chunk, this, LockType.Read);
|
||||
}
|
||||
|
||||
|
||||
// Track contention
|
||||
ChunkThreadingDiagnostics.TrackLockContention(chunk);
|
||||
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Tries to acquire a write lock on a chunk.
|
||||
/// </summary>
|
||||
@ -111,18 +111,18 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
var lockObj = _locks.GetOrAdd(chunk, _ => new ChunkLock());
|
||||
_lastAccessTime[chunk] = DateTime.UtcNow;
|
||||
|
||||
|
||||
if (lockObj.TryEnterWriteLock(timeout))
|
||||
{
|
||||
return new LockReleaser(lockObj, chunk, this, LockType.Write);
|
||||
}
|
||||
|
||||
|
||||
// Track contention
|
||||
ChunkThreadingDiagnostics.TrackLockContention(chunk);
|
||||
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Cleans up unused locks.
|
||||
/// </summary>
|
||||
@ -130,10 +130,10 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
var threshold = now.AddMinutes(-_cleanupIntervalMinutes);
|
||||
|
||||
|
||||
foreach (var chunk in _lastAccessTime.Keys)
|
||||
{
|
||||
if (_lastAccessTime.TryGetValue(chunk, out var lastAccess) &&
|
||||
if (_lastAccessTime.TryGetValue(chunk, out var lastAccess) &&
|
||||
lastAccess < threshold &&
|
||||
_locks.TryGetValue(chunk, out var lockObj))
|
||||
{
|
||||
@ -149,23 +149,23 @@ namespace AdvChkSys.Threading
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Disposes resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_cleanupTimer.Dispose();
|
||||
|
||||
|
||||
foreach (var lockObj in _locks.Values)
|
||||
{
|
||||
lockObj.Dispose();
|
||||
}
|
||||
|
||||
|
||||
_locks.Clear();
|
||||
_lastAccessTime.Clear();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Type of lock.
|
||||
/// </summary>
|
||||
@ -174,28 +174,28 @@ namespace AdvChkSys.Threading
|
||||
Read,
|
||||
Write
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Wrapper around ReaderWriterLockSlim.
|
||||
/// </summary>
|
||||
private class ChunkLock : IDisposable
|
||||
{
|
||||
private readonly ReaderWriterLockSlim _lock = new(LockRecursionPolicy.SupportsRecursion);
|
||||
|
||||
|
||||
public void EnterReadLock() => _lock.EnterReadLock();
|
||||
public void ExitReadLock() => _lock.ExitReadLock();
|
||||
public void EnterWriteLock() => _lock.EnterWriteLock();
|
||||
public void ExitWriteLock() => _lock.ExitWriteLock();
|
||||
|
||||
|
||||
public bool TryEnterReadLock(TimeSpan timeout) => _lock.TryEnterReadLock(timeout);
|
||||
public bool TryEnterWriteLock(TimeSpan timeout) => _lock.TryEnterWriteLock(timeout);
|
||||
|
||||
|
||||
public bool IsReadLockHeld => _lock.IsReadLockHeld;
|
||||
public bool IsWriteLockHeld => _lock.IsWriteLockHeld;
|
||||
|
||||
|
||||
public void Dispose() => _lock.Dispose();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Releases a lock when disposed.
|
||||
/// </summary>
|
||||
@ -206,7 +206,7 @@ namespace AdvChkSys.Threading
|
||||
private readonly ChunkThreadSafetyManager _parent;
|
||||
private readonly LockType _lockType;
|
||||
private bool _disposed;
|
||||
|
||||
|
||||
public LockReleaser(ChunkLock lockObj, IChunk chunk, ChunkThreadSafetyManager parent, LockType lockType)
|
||||
{
|
||||
_lock = lockObj;
|
||||
@ -214,7 +214,7 @@ namespace AdvChkSys.Threading
|
||||
_parent = parent;
|
||||
_lockType = lockType;
|
||||
}
|
||||
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (!_disposed)
|
||||
@ -227,7 +227,7 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
_lock.ExitWriteLock();
|
||||
}
|
||||
|
||||
|
||||
_parent._lastAccessTime[_chunk] = DateTime.UtcNow;
|
||||
_disposed = true;
|
||||
}
|
||||
|
||||
@ -11,7 +11,7 @@ namespace AdvChkSys.Threading
|
||||
private static int _defaultMaxDegreeOfParallelism = Environment.ProcessorCount;
|
||||
private static int _chunkOperationTimeout = 30000; // 30 seconds
|
||||
private static int _lockCleanupInterval = 10; // 10 minutes
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the default maximum degree of parallelism for chunk operations.
|
||||
/// </summary>
|
||||
@ -26,7 +26,7 @@ namespace AdvChkSys.Threading
|
||||
ChunkTaskScheduler.MaxDegreeOfParallelism = value;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the timeout in milliseconds for chunk operations.
|
||||
/// </summary>
|
||||
@ -40,7 +40,7 @@ namespace AdvChkSys.Threading
|
||||
_chunkOperationTimeout = value;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the interval in minutes for cleaning up unused locks.
|
||||
/// </summary>
|
||||
@ -54,17 +54,17 @@ namespace AdvChkSys.Threading
|
||||
_lockCleanupInterval = value;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Creates a cancellation token with the default timeout.
|
||||
/// </summary>
|
||||
public static CancellationToken CreateTimeoutToken(CancellationToken cancellationToken = default)
|
||||
{
|
||||
return ChunkTaskScheduler.CreateTimeoutToken(
|
||||
TimeSpan.FromMilliseconds(_chunkOperationTimeout),
|
||||
TimeSpan.FromMilliseconds(_chunkOperationTimeout),
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Configures the system for high throughput (more parallelism, longer timeouts).
|
||||
/// </summary>
|
||||
@ -74,7 +74,7 @@ namespace AdvChkSys.Threading
|
||||
ChunkOperationTimeoutMs = 60000; // 1 minute
|
||||
LockCleanupIntervalMinutes = 30;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Configures the system for low latency (less parallelism, shorter timeouts).
|
||||
/// </summary>
|
||||
@ -84,7 +84,7 @@ namespace AdvChkSys.Threading
|
||||
ChunkOperationTimeoutMs = 15000; // 15 seconds
|
||||
LockCleanupIntervalMinutes = 5;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Configures the system for memory efficiency (less parallelism, more aggressive cleanup).
|
||||
/// </summary>
|
||||
|
||||
@ -16,19 +16,19 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
// Track operation durations
|
||||
private static readonly ConcurrentDictionary<string, List<long>> _operationDurations = new();
|
||||
|
||||
|
||||
// Track lock contention
|
||||
private static readonly ConcurrentDictionary<IChunk, int> _lockContentionCount = new();
|
||||
|
||||
|
||||
// Track active operations
|
||||
private static readonly ConcurrentDictionary<Guid, (string Operation, DateTime StartTime, IChunk Chunk)> _activeOperations = new();
|
||||
|
||||
|
||||
// Lock for thread safety
|
||||
private static readonly object _lock = new();
|
||||
|
||||
|
||||
// Stopwatch for timing
|
||||
private static readonly Stopwatch _stopwatch = Stopwatch.StartNew();
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Tracks the duration of an operation.
|
||||
/// </summary>
|
||||
@ -38,7 +38,7 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
var operationId = Guid.NewGuid();
|
||||
var startTime = _stopwatch.ElapsedMilliseconds;
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
action();
|
||||
@ -46,7 +46,7 @@ namespace AdvChkSys.Threading
|
||||
finally
|
||||
{
|
||||
var duration = _stopwatch.ElapsedMilliseconds - startTime;
|
||||
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_operationDurations.TryGetValue(operationName, out var durations))
|
||||
@ -54,9 +54,9 @@ namespace AdvChkSys.Threading
|
||||
durations = new List<long>();
|
||||
_operationDurations[operationName] = durations;
|
||||
}
|
||||
|
||||
|
||||
durations.Add(duration);
|
||||
|
||||
|
||||
// Keep only the last 1000 durations
|
||||
if (durations.Count > 1000)
|
||||
{
|
||||
@ -65,7 +65,7 @@ namespace AdvChkSys.Threading
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Tracks the start of an operation on a chunk.
|
||||
/// </summary>
|
||||
@ -78,7 +78,7 @@ namespace AdvChkSys.Threading
|
||||
_activeOperations[operationId] = (operationName, DateTime.UtcNow, chunk);
|
||||
return operationId;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Tracks the end of an operation.
|
||||
/// </summary>
|
||||
@ -88,7 +88,7 @@ namespace AdvChkSys.Threading
|
||||
if (_activeOperations.TryRemove(operationId, out var info))
|
||||
{
|
||||
var duration = (DateTime.UtcNow - info.StartTime).TotalMilliseconds;
|
||||
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_operationDurations.TryGetValue(info.Operation, out var durations))
|
||||
@ -96,9 +96,9 @@ namespace AdvChkSys.Threading
|
||||
durations = new List<long>();
|
||||
_operationDurations[info.Operation] = durations;
|
||||
}
|
||||
|
||||
|
||||
durations.Add((long)duration);
|
||||
|
||||
|
||||
// Keep only the last 1000 durations
|
||||
if (durations.Count > 1000)
|
||||
{
|
||||
@ -107,7 +107,7 @@ namespace AdvChkSys.Threading
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Tracks lock contention on a chunk.
|
||||
/// </summary>
|
||||
@ -116,14 +116,14 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
_lockContentionCount.AddOrUpdate(chunk, 1, (_, count) => count + 1);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets statistics about operation durations.
|
||||
/// </summary>
|
||||
public static Dictionary<string, (long Min, long Max, double Average, int Count)> GetOperationStatistics()
|
||||
{
|
||||
var result = new Dictionary<string, (long Min, long Max, double Average, int Count)>();
|
||||
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
foreach (var kvp in _operationDurations)
|
||||
@ -140,10 +140,10 @@ namespace AdvChkSys.Threading
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets the chunks with the most lock contention.
|
||||
/// </summary>
|
||||
@ -156,7 +156,7 @@ namespace AdvChkSys.Threading
|
||||
.Select(kvp => (kvp.Key, kvp.Value))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets information about currently active operations.
|
||||
/// </summary>
|
||||
@ -172,7 +172,7 @@ namespace AdvChkSys.Threading
|
||||
.OrderByDescending(x => x.Item2)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets the total number of tracked operations.
|
||||
/// </summary>
|
||||
@ -183,7 +183,7 @@ namespace AdvChkSys.Threading
|
||||
return _operationDurations.Values.Sum(list => list.Count);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of active operations.
|
||||
/// </summary>
|
||||
@ -191,7 +191,7 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
return _activeOperations.Count;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets the total number of lock contentions.
|
||||
/// </summary>
|
||||
@ -199,7 +199,7 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
return _lockContentionCount.Values.Sum();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Clears all diagnostic data.
|
||||
/// </summary>
|
||||
@ -212,18 +212,18 @@ namespace AdvChkSys.Threading
|
||||
// Don't clear active operations as they're still in progress
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets a comprehensive diagnostic report.
|
||||
/// </summary>
|
||||
public static string GenerateDiagnosticReport()
|
||||
{
|
||||
var report = new System.Text.StringBuilder();
|
||||
|
||||
|
||||
report.AppendLine("=== Chunk Threading Diagnostic Report ===");
|
||||
report.AppendLine($"Generated: {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC");
|
||||
report.AppendLine();
|
||||
|
||||
|
||||
// Operation statistics
|
||||
report.AppendLine("== Operation Statistics ==");
|
||||
var stats = GetOperationStatistics();
|
||||
@ -236,7 +236,7 @@ namespace AdvChkSys.Threading
|
||||
report.AppendLine($" Avg: {kvp.Value.Average:F2}ms");
|
||||
}
|
||||
report.AppendLine();
|
||||
|
||||
|
||||
// Lock contention
|
||||
report.AppendLine("== Lock Contention ==");
|
||||
var contentions = GetTopContentionChunks(10);
|
||||
@ -246,7 +246,7 @@ namespace AdvChkSys.Threading
|
||||
}
|
||||
report.AppendLine($"Total contentions: {GetTotalLockContentionCount()}");
|
||||
report.AppendLine();
|
||||
|
||||
|
||||
// Active operations
|
||||
report.AppendLine("== Active Operations ==");
|
||||
var activeOps = GetActiveOperations();
|
||||
@ -255,10 +255,10 @@ namespace AdvChkSys.Threading
|
||||
report.AppendLine($"{operation} on Chunk ({chunk.X}, {chunk.Y}): {duration.TotalMilliseconds:F2}ms");
|
||||
}
|
||||
report.AppendLine($"Total active operations: {GetActiveOperationCount()}");
|
||||
|
||||
|
||||
return report.ToString();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Logs a diagnostic event.
|
||||
/// </summary>
|
||||
|
||||
@ -76,7 +76,7 @@ namespace AdvChkSys.Threading
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var chunks = new List<Chunk.Chunk2D<T>>();
|
||||
|
||||
|
||||
// Collect chunks in the region
|
||||
for (int x = minX; x <= maxX; x++)
|
||||
{
|
||||
@ -89,7 +89,7 @@ namespace AdvChkSys.Threading
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Process in parallel
|
||||
await ChunkTaskScheduler.RunBatchParallelAsync(
|
||||
chunks.Select(c => new Action(() => action(c))).ToArray(),
|
||||
@ -119,7 +119,7 @@ namespace AdvChkSys.Threading
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var chunks = new List<Chunk.Chunk3D<T>>();
|
||||
|
||||
|
||||
// Collect chunks in the region
|
||||
for (int x = minX; x <= maxX; x++)
|
||||
{
|
||||
@ -135,7 +135,7 @@ namespace AdvChkSys.Threading
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Process in parallel
|
||||
await ChunkTaskScheduler.RunBatchParallelAsync(
|
||||
chunks.Select(c => new Action(() => action(c))).ToArray(),
|
||||
@ -165,7 +165,7 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
// Create a loading priority system if not already integrated
|
||||
var loadingPriority = new ChunkLoadingPriority();
|
||||
|
||||
|
||||
// Enqueue all chunks in the region
|
||||
var tasks = new List<Task>();
|
||||
for (int x = minX; x <= maxX; x++)
|
||||
@ -174,17 +174,17 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
break;
|
||||
|
||||
|
||||
// Skip if already loaded
|
||||
if (manager.IsChunkLoaded(x, y))
|
||||
continue;
|
||||
|
||||
|
||||
// Enqueue the request
|
||||
var request = loadingPriority.EnqueueRequest(x, y, width, height, priority);
|
||||
|
||||
|
||||
// Create a task that completes when the chunk is loaded
|
||||
var tcs = new TaskCompletionSource<bool>();
|
||||
|
||||
|
||||
void Handler(object? sender, ChunkLoadingPriority.ChunkLoadRequest completedRequest)
|
||||
{
|
||||
if (completedRequest.RequestId == request.RequestId)
|
||||
@ -193,24 +193,24 @@ namespace AdvChkSys.Threading
|
||||
tcs.TrySetResult(true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
loadingPriority.RequestCompleted += Handler;
|
||||
|
||||
|
||||
// Add timeout to prevent indefinite waiting
|
||||
_ = Task.Delay(30000, cancellationToken).ContinueWith(t =>
|
||||
_ = Task.Delay(30000, cancellationToken).ContinueWith(t =>
|
||||
{
|
||||
loadingPriority.RequestCompleted -= Handler;
|
||||
if (!t.IsCanceled)
|
||||
tcs.TrySetResult(false);
|
||||
}, cancellationToken);
|
||||
|
||||
|
||||
tasks.Add(tcs.Task);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Wait for all chunks to be loaded
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
|
||||
|
||||
// Clean up
|
||||
await loadingPriority.ShutdownAsync().ConfigureAwait(false);
|
||||
}
|
||||
@ -240,7 +240,7 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
// Create a loading priority system if not already integrated
|
||||
var loadingPriority = new ChunkLoadingPriority();
|
||||
|
||||
|
||||
// Enqueue all chunks in the region
|
||||
var tasks = new List<Task>();
|
||||
for (int x = minX; x <= maxX; x++)
|
||||
@ -251,17 +251,17 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
break;
|
||||
|
||||
|
||||
// Skip if already loaded
|
||||
if (manager.IsChunkLoaded(x, y, z))
|
||||
continue;
|
||||
|
||||
|
||||
// Enqueue the request
|
||||
var request = loadingPriority.EnqueueRequest(x, y, z, width, height, depth, priority);
|
||||
|
||||
|
||||
// Create a task that completes when the chunk is loaded
|
||||
var tcs = new TaskCompletionSource<bool>();
|
||||
|
||||
|
||||
void Handler(object? sender, ChunkLoadingPriority.ChunkLoadRequest completedRequest)
|
||||
{
|
||||
if (completedRequest.RequestId == request.RequestId)
|
||||
@ -270,25 +270,25 @@ namespace AdvChkSys.Threading
|
||||
tcs.TrySetResult(true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
loadingPriority.RequestCompleted += Handler;
|
||||
|
||||
|
||||
// Add timeout to prevent indefinite waiting
|
||||
_ = Task.Delay(30000, cancellationToken).ContinueWith(t =>
|
||||
_ = Task.Delay(30000, cancellationToken).ContinueWith(t =>
|
||||
{
|
||||
loadingPriority.RequestCompleted -= Handler;
|
||||
if (!t.IsCanceled)
|
||||
tcs.TrySetResult(false);
|
||||
}, cancellationToken);
|
||||
|
||||
|
||||
tasks.Add(tcs.Task);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Wait for all chunks to be loaded
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
|
||||
|
||||
// Clean up
|
||||
await loadingPriority.ShutdownAsync().ConfigureAwait(false);
|
||||
}
|
||||
@ -312,21 +312,21 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
// Get all loaded chunks
|
||||
var chunks = manager.GetAllChunks().ToArray();
|
||||
|
||||
|
||||
// Filter chunks outside the region
|
||||
var chunksToUnload = chunks.Where(c =>
|
||||
var chunksToUnload = chunks.Where(c =>
|
||||
c.X < minX || c.X > maxX || c.Y < minY || c.Y > maxY).ToArray();
|
||||
|
||||
|
||||
// Unload in parallel
|
||||
var options = new ParallelOptions
|
||||
{
|
||||
MaxDegreeOfParallelism = maxDegreeOfParallelism ?? Environment.ProcessorCount,
|
||||
CancellationToken = cancellationToken
|
||||
};
|
||||
|
||||
await Task.Run(() =>
|
||||
|
||||
await Task.Run(() =>
|
||||
{
|
||||
Parallel.ForEach(chunksToUnload, options, chunk =>
|
||||
Parallel.ForEach(chunksToUnload, options, chunk =>
|
||||
{
|
||||
manager.UnloadChunk(chunk.X, chunk.Y);
|
||||
});
|
||||
@ -354,23 +354,23 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
// Get all loaded chunks
|
||||
var chunks = manager.GetAllChunks().ToArray();
|
||||
|
||||
|
||||
// Filter chunks outside the region
|
||||
var chunksToUnload = chunks.Where(c =>
|
||||
c.X < minX || c.X > maxX ||
|
||||
c.Y < minY || c.Y > maxY ||
|
||||
var chunksToUnload = chunks.Where(c =>
|
||||
c.X < minX || c.X > maxX ||
|
||||
c.Y < minY || c.Y > maxY ||
|
||||
c.Z < minZ || c.Z > maxZ).ToArray();
|
||||
|
||||
|
||||
// Unload in parallel
|
||||
var options = new ParallelOptions
|
||||
{
|
||||
MaxDegreeOfParallelism = maxDegreeOfParallelism ?? Environment.ProcessorCount,
|
||||
CancellationToken = cancellationToken
|
||||
};
|
||||
|
||||
await Task.Run(() =>
|
||||
|
||||
await Task.Run(() =>
|
||||
{
|
||||
Parallel.ForEach(chunksToUnload, options, chunk =>
|
||||
Parallel.ForEach(chunksToUnload, options, chunk =>
|
||||
{
|
||||
manager.UnloadChunk(chunk.X, chunk.Y, chunk.Z);
|
||||
});
|
||||
|
||||
@ -35,21 +35,21 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
// Generate spiral coordinates
|
||||
var coordinates = GenerateSpiralCoordinates(centerX, centerY, radius).ToArray();
|
||||
|
||||
|
||||
// Process in batches to maintain the spiral ordering while still using parallelism
|
||||
int batchSize = Math.Max(1, (int)Math.Sqrt(coordinates.Length));
|
||||
int batchCount = (coordinates.Length + batchSize - 1) / batchSize;
|
||||
|
||||
|
||||
for (int i = 0; i < batchCount; i++)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
break;
|
||||
|
||||
|
||||
var batchCoords = coordinates
|
||||
.Skip(i * batchSize)
|
||||
.Take(batchSize)
|
||||
.ToArray();
|
||||
|
||||
|
||||
var tasks = new List<Task>();
|
||||
foreach (var (x, y) in batchCoords)
|
||||
{
|
||||
@ -59,14 +59,14 @@ namespace AdvChkSys.Threading
|
||||
tasks.Add(processor(chunk));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (tasks.Count > 0)
|
||||
{
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Generates coordinates in a spiral pattern from the center outward.
|
||||
/// </summary>
|
||||
@ -74,7 +74,7 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
// Start with the center
|
||||
yield return (centerX, centerY);
|
||||
|
||||
|
||||
// Spiral outward
|
||||
for (int layer = 1; layer <= radius; layer++)
|
||||
{
|
||||
@ -83,19 +83,19 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
yield return (x, centerY - layer);
|
||||
}
|
||||
|
||||
|
||||
// Right edge (moving down)
|
||||
for (int y = centerY - layer + 1; y <= centerY + layer; y++)
|
||||
{
|
||||
yield return (centerX + layer, y);
|
||||
}
|
||||
|
||||
|
||||
// Bottom edge (moving left)
|
||||
for (int x = centerX + layer - 1; x >= centerX - layer; x--)
|
||||
{
|
||||
yield return (x, centerY + layer);
|
||||
}
|
||||
|
||||
|
||||
// Left edge (moving up)
|
||||
for (int y = centerY + layer - 1; y >= centerY - layer; y--)
|
||||
{
|
||||
@ -103,7 +103,7 @@ namespace AdvChkSys.Threading
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Processes chunks with dependency awareness.
|
||||
/// </summary>
|
||||
@ -121,7 +121,7 @@ namespace AdvChkSys.Threading
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var chunks = manager.GetAllChunks().ToArray();
|
||||
|
||||
|
||||
await ChunkParallelProcessor.ProcessChunksWithDependenciesAsync(
|
||||
chunks,
|
||||
chunk => processor((Chunk2D<T>)chunk),
|
||||
@ -129,7 +129,7 @@ namespace AdvChkSys.Threading
|
||||
maxDegreeOfParallelism,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Processes chunks with dependency awareness.
|
||||
/// </summary>
|
||||
@ -147,7 +147,7 @@ namespace AdvChkSys.Threading
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var chunks = manager.GetAllChunks().ToArray();
|
||||
|
||||
|
||||
await ChunkParallelProcessor.ProcessChunksWithDependenciesAsync(
|
||||
chunks,
|
||||
chunk => processor((Chunk3D<T>)chunk),
|
||||
@ -155,7 +155,7 @@ namespace AdvChkSys.Threading
|
||||
maxDegreeOfParallelism,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Processes chunks with thread safety.
|
||||
/// </summary>
|
||||
@ -172,22 +172,22 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
var chunks = manager.GetAllChunks().ToArray();
|
||||
var threadingManager = ChunkThreadingManager.Instance;
|
||||
|
||||
|
||||
var options = new ParallelOptions
|
||||
{
|
||||
MaxDegreeOfParallelism = maxDegreeOfParallelism ?? ChunkThreadingConfiguration.DefaultMaxDegreeOfParallelism,
|
||||
CancellationToken = cancellationToken
|
||||
};
|
||||
|
||||
await Task.Run(() => Parallel.ForEach(chunks, options, async chunk =>
|
||||
|
||||
await Task.Run(() => Parallel.ForEach(chunks, options, async chunk =>
|
||||
{
|
||||
await threadingManager.WithLockAsync(chunk, async () =>
|
||||
await threadingManager.WithLockAsync(chunk, async () =>
|
||||
{
|
||||
await processor(chunk).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Processes chunks with thread safety.
|
||||
/// </summary>
|
||||
@ -204,16 +204,16 @@ namespace AdvChkSys.Threading
|
||||
{
|
||||
var chunks = manager.GetAllChunks().ToArray();
|
||||
var threadingManager = ChunkThreadingManager.Instance;
|
||||
|
||||
|
||||
var options = new ParallelOptions
|
||||
{
|
||||
MaxDegreeOfParallelism = maxDegreeOfParallelism ?? ChunkThreadingConfiguration.DefaultMaxDegreeOfParallelism,
|
||||
CancellationToken = cancellationToken
|
||||
};
|
||||
|
||||
await Task.Run(() => Parallel.ForEach(chunks, options, async chunk =>
|
||||
|
||||
await Task.Run(() => Parallel.ForEach(chunks, options, async chunk =>
|
||||
{
|
||||
await threadingManager.WithLockAsync(chunk, async () =>
|
||||
await threadingManager.WithLockAsync(chunk, async () =>
|
||||
{
|
||||
await processor(chunk).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
@ -16,7 +16,7 @@ namespace AdvChkSys.Threading
|
||||
private static bool _currentThreadIsProcessingItems;
|
||||
|
||||
// The list of tasks to be executed
|
||||
private readonly LinkedList<Task> _tasks = new LinkedList<Task>();
|
||||
private readonly LinkedList<Task> _tasks = new();
|
||||
|
||||
// The maximum concurrency level allowed by this scheduler.
|
||||
private int _maximumConcurrencyLevel;
|
||||
|
||||
@ -115,8 +115,8 @@ namespace AdvChkSys.Util
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
foreach (var node in _lruList)
|
||||
yield return node.value;
|
||||
foreach (var (key, value) in _lruList)
|
||||
yield return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user