Use BlockingCollection

This commit is contained in:
Bond_009
2023-04-14 21:38:12 +02:00
parent 858dadcdd1
commit 33f97045f9
2 changed files with 33 additions and 48 deletions

View File

@@ -2,44 +2,47 @@
using System;
using System.Collections.Concurrent;
using System.Threading;
using SQLitePCL.pretty;
namespace Emby.Server.Implementations.Data;
public sealed class ConnectionPool : IDisposable
{
private readonly int _count;
private readonly SemaphoreSlim _lock;
private readonly ConcurrentQueue<SQLiteDatabaseConnection> _connections = new ConcurrentQueue<SQLiteDatabaseConnection>();
private readonly BlockingCollection<SQLiteDatabaseConnection> _connections = new();
private bool _disposed;
public ConnectionPool(int count, Func<SQLiteDatabaseConnection> factory)
{
_count = count;
_lock = new SemaphoreSlim(count, count);
for (int i = 0; i < count; i++)
{
_connections.Enqueue(factory.Invoke());
_connections.Add(factory.Invoke());
}
}
public ManagedConnection GetConnection()
{
_lock.Wait();
if (!_connections.TryDequeue(out var connection))
if (_disposed)
{
_lock.Release();
throw new InvalidOperationException();
ThrowObjectDisposedException();
}
return new ManagedConnection(connection, this);
return new ManagedConnection(_connections.Take(), this);
void ThrowObjectDisposedException()
{
throw new ObjectDisposedException(GetType().Name);
}
}
public void Return(SQLiteDatabaseConnection connection)
{
_connections.Enqueue(connection);
_lock.Release();
if (_disposed)
{
connection.Dispose();
return;
}
_connections.Add(connection);
}
public void Dispose()
@@ -49,20 +52,11 @@ public sealed class ConnectionPool : IDisposable
return;
}
for (int i = 0; i < _count; i++)
foreach (var connection in _connections)
{
_lock.Wait();
if (!_connections.TryDequeue(out var connection))
{
_lock.Release();
throw new InvalidOperationException();
}
connection.Dispose();
}
_lock.Dispose();
_disposed = true;
}
}