ConnectionPool.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Concurrent;
  4. using SQLitePCL.pretty;
  5. namespace Emby.Server.Implementations.Data;
  6. public sealed class ConnectionPool : IDisposable
  7. {
  8. private readonly BlockingCollection<SQLiteDatabaseConnection> _connections = new();
  9. private bool _disposed;
  10. public ConnectionPool(int count, Func<SQLiteDatabaseConnection> factory)
  11. {
  12. for (int i = 0; i < count; i++)
  13. {
  14. _connections.Add(factory.Invoke());
  15. }
  16. }
  17. public ManagedConnection GetConnection()
  18. {
  19. if (_disposed)
  20. {
  21. ThrowObjectDisposedException();
  22. }
  23. return new ManagedConnection(_connections.Take(), this);
  24. void ThrowObjectDisposedException()
  25. {
  26. throw new ObjectDisposedException(GetType().Name);
  27. }
  28. }
  29. public void Return(SQLiteDatabaseConnection connection)
  30. {
  31. if (_disposed)
  32. {
  33. connection.Dispose();
  34. return;
  35. }
  36. _connections.Add(connection);
  37. }
  38. public void Dispose()
  39. {
  40. if (_disposed)
  41. {
  42. return;
  43. }
  44. foreach (var connection in _connections)
  45. {
  46. connection.Dispose();
  47. }
  48. _disposed = true;
  49. }
  50. }