make database access perform more realistically

This commit is contained in:
2026-09-15 14:28:18 +01:00
parent 54ca937780
commit 0d19a1f171
2 changed files with 21 additions and 0 deletions
+1
View File
@@ -7,6 +7,7 @@ obj/
.vscode/
*.user
*.suo
.idea
## Dotnet CLI
.dotnet/
+20
View File
@@ -18,6 +18,21 @@ public class DbContext
// maintains a separate set per entity type.
private readonly Dictionary<Type, Collection<DbBase>> _tables = new();
// -----------------------------------------------------------------
// Simulated DB latency. Every "round trip" through this context —
// Attach, Save, Find, IsTracked, Tracked — sleeps for this long, the
// way a real database makes every call pay a network + query cost.
// Deliberately on by default: the console demo and the tests are
// supposed to feel sluggish, so the cost of persistence becomes
// visible. Set to TimeSpan.Zero for an instant fake.
// -----------------------------------------------------------------
/// <summary>
/// Simulated latency per DB operation. Default 200 ms.
/// </summary>
public static TimeSpan Latency { get; set; } = TimeSpan.FromMilliseconds(200);
private static void SimulateLatency() => Thread.Sleep(Latency);
/// <summary>
/// Get or create the per-type table for <typeparamref name="T"/>.
/// This mirrors EF's <see cref="DbSet{T}"/> / <c>Set&lt;T&gt;</c> accessor.
@@ -55,6 +70,7 @@ public class DbContext
/// </summary>
public void Attach(DbBase entity)
{
SimulateLatency();
ArgumentNullException.ThrowIfNull(entity);
entity.DbContext = this;
var table = TableFor(entity.GetType());
@@ -70,6 +86,7 @@ public class DbContext
/// </summary>
public int Save()
{
SimulateLatency();
var saved = 0;
foreach (var table in _tables.Values)
foreach (var entity in table)
@@ -95,6 +112,7 @@ public class DbContext
/// <returns>The first matching entity, or <c>null</c> when no match.</returns>
public T? Find<T>(Predicate<T> predicate) where T : DbBase
{
SimulateLatency();
var table = Table<T>();
foreach (var e in table)
if (e is T candidate && predicate(candidate))
@@ -108,6 +126,7 @@ public class DbContext
/// </summary>
public bool IsTracked(DbBase entity)
{
SimulateLatency();
foreach (var table in _tables.Values)
if (table.Contains(entity))
return true;
@@ -122,6 +141,7 @@ public class DbContext
{
get
{
SimulateLatency();
var all = new List<DbBase>();
foreach (var table in _tables.Values)
all.AddRange(table);