aboutsummaryrefslogtreecommitdiff
path: root/Emby.Server.Implementations/Data/ConnectionPool.cs
blob: 86a125ba51b20a103bbdf78a656dd43d3c57dcf5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#pragma warning disable CS1591

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 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());
        }
    }

    public ManagedConnection GetConnection()
    {
        _lock.Wait();
        if (!_connections.TryDequeue(out var connection))
        {
            _lock.Release();
            throw new InvalidOperationException();
        }

        return new ManagedConnection(connection, this);
    }

    public void Return(SQLiteDatabaseConnection connection)
    {
        _connections.Enqueue(connection);
        _lock.Release();
    }

    public void Dispose()
    {
        if (_disposed)
        {
            return;
        }

        for (int i = 0; i < _count; i++)
        {
            _lock.Wait();
            if (!_connections.TryDequeue(out var connection))
            {
                _lock.Release();
                throw new InvalidOperationException();
            }

            connection.Dispose();
        }

        _lock.Dispose();

        _disposed = true;
    }
}