jellyfin/Emby.Server.Implementations/Data/ConnectionPool.cs

80 lines
2 KiB
C#
Raw Normal View History

2023-04-14 13:43:56 +02:00
using System;
using System.Collections.Concurrent;
using SQLitePCL.pretty;
namespace Emby.Server.Implementations.Data;
/// <summary>
/// A pool of SQLite Database connections.
/// </summary>
2023-04-14 13:43:56 +02:00
public sealed class ConnectionPool : IDisposable
{
2023-04-14 21:38:12 +02:00
private readonly BlockingCollection<SQLiteDatabaseConnection> _connections = new();
2023-04-14 13:43:56 +02:00
private bool _disposed;
/// <summary>
/// Initializes a new instance of the <see cref="ConnectionPool" /> class.
/// </summary>
/// <param name="count">The number of database connection to create.</param>
/// <param name="factory">Factory function to create the database connections.</param>
2023-04-14 13:43:56 +02:00
public ConnectionPool(int count, Func<SQLiteDatabaseConnection> factory)
{
for (int i = 0; i < count; i++)
{
2023-04-14 21:38:12 +02:00
_connections.Add(factory.Invoke());
2023-04-14 13:43:56 +02:00
}
}
/// <summary>
/// Gets a database connection from the pool if one is available, otherwise blocks.
/// </summary>
/// <returns>A database connection.</returns>
2023-04-14 13:43:56 +02:00
public ManagedConnection GetConnection()
{
2023-04-14 21:38:12 +02:00
if (_disposed)
2023-04-14 13:43:56 +02:00
{
2023-04-14 21:38:12 +02:00
ThrowObjectDisposedException();
2023-04-14 13:43:56 +02:00
}
2023-04-14 21:38:12 +02:00
return new ManagedConnection(_connections.Take(), this);
2023-05-04 14:42:39 +02:00
static void ThrowObjectDisposedException()
2023-04-14 21:38:12 +02:00
{
2023-05-04 14:42:39 +02:00
throw new ObjectDisposedException(nameof(ConnectionPool));
2023-04-14 21:38:12 +02:00
}
2023-04-14 13:43:56 +02:00
}
/// <summary>
/// Return a database connection to the pool.
/// </summary>
/// <param name="connection">The database connection to return.</param>
2023-04-14 13:43:56 +02:00
public void Return(SQLiteDatabaseConnection connection)
{
2023-04-14 21:38:12 +02:00
if (_disposed)
{
connection.Dispose();
return;
}
_connections.Add(connection);
2023-04-14 13:43:56 +02:00
}
/// <inheritdoc />
2023-04-14 13:43:56 +02:00
public void Dispose()
{
if (_disposed)
{
return;
}
2023-04-14 21:38:12 +02:00
foreach (var connection in _connections)
2023-04-14 13:43:56 +02:00
{
connection.Dispose();
}
2023-04-24 13:08:46 +02:00
_connections.Dispose();
2023-04-14 13:43:56 +02:00
_disposed = true;
}
}