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

63 lines
1.3 KiB
C#
Raw Normal View History

2023-04-14 11:43:56 +00:00
#pragma warning disable CS1591
using System;
using System.Collections.Concurrent;
using SQLitePCL.pretty;
namespace Emby.Server.Implementations.Data;
public sealed class ConnectionPool : IDisposable
{
2023-04-14 19:38:12 +00:00
private readonly BlockingCollection<SQLiteDatabaseConnection> _connections = new();
2023-04-14 11:43:56 +00:00
private bool _disposed;
public ConnectionPool(int count, Func<SQLiteDatabaseConnection> factory)
{
for (int i = 0; i < count; i++)
{
2023-04-14 19:38:12 +00:00
_connections.Add(factory.Invoke());
2023-04-14 11:43:56 +00:00
}
}
public ManagedConnection GetConnection()
{
2023-04-14 19:38:12 +00:00
if (_disposed)
2023-04-14 11:43:56 +00:00
{
2023-04-14 19:38:12 +00:00
ThrowObjectDisposedException();
2023-04-14 11:43:56 +00:00
}
2023-04-14 19:38:12 +00:00
return new ManagedConnection(_connections.Take(), this);
void ThrowObjectDisposedException()
{
throw new ObjectDisposedException(GetType().Name);
}
2023-04-14 11:43:56 +00:00
}
public void Return(SQLiteDatabaseConnection connection)
{
2023-04-14 19:38:12 +00:00
if (_disposed)
{
connection.Dispose();
return;
}
_connections.Add(connection);
2023-04-14 11:43:56 +00:00
}
public void Dispose()
{
if (_disposed)
{
return;
}
2023-04-14 19:38:12 +00:00
foreach (var connection in _connections)
2023-04-14 11:43:56 +00:00
{
connection.Dispose();
}
_disposed = true;
}
}