DatabaseContextPool.cs 939 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. namespace Benchmarks.Model;
  2. using System.Collections.Concurrent;
  3. using Microsoft.EntityFrameworkCore;
  4. public sealed class DatabaseContextPool<TContext> where TContext : DbContext
  5. {
  6. private readonly ConcurrentBag<TContext> _pool = new();
  7. private readonly Func<TContext> _factory;
  8. private readonly int _maxSize;
  9. public DatabaseContextPool(Func<TContext> factory, int maxSize)
  10. {
  11. _factory = factory;
  12. _maxSize = maxSize;
  13. }
  14. public TContext Rent()
  15. {
  16. if (_pool.TryTake(out var ctx))
  17. {
  18. ctx.ChangeTracker.Clear();
  19. return ctx;
  20. }
  21. return _factory();
  22. }
  23. public void Return(TContext context)
  24. {
  25. if (_pool.Count >= _maxSize)
  26. {
  27. context.Dispose();
  28. return;
  29. }
  30. context.ChangeTracker.Clear();
  31. _pool.Add(context);
  32. }
  33. }