make database access perform more realistically
This commit is contained in:
@@ -7,6 +7,7 @@ obj/
|
||||
.vscode/
|
||||
*.user
|
||||
*.suo
|
||||
.idea
|
||||
|
||||
## Dotnet CLI
|
||||
.dotnet/
|
||||
|
||||
@@ -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<T></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);
|
||||
|
||||
Reference in New Issue
Block a user