aboutsummaryrefslogtreecommitdiff
path: root/Emby.Server.Implementations/Data/ConnectionPool.cs
blob: 5ea7e934ffd86693eb979f4980f32e0839379a02 (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
69
70
71
72
73
74
75
76
77
78
79
using System;
using System.Collections.Concurrent;
using SQLitePCL.pretty;

namespace Emby.Server.Implementations.Data;

/// <summary>
/// A pool of SQLite Database connections.
/// </summary>
public sealed class ConnectionPool : IDisposable
{
    private readonly BlockingCollection<SQLiteDatabaseConnection> _connections = new();
    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>
    public ConnectionPool(int count, Func<SQLiteDatabaseConnection> factory)
    {
        for (int i = 0; i < count; i++)
        {
            _connections.Add(factory.Invoke());
        }
    }

    /// <summary>
    /// Gets a database connection from the pool if one is available, otherwise blocks.
    /// </summary>
    /// <returns>A database connection.</returns>
    public ManagedConnection GetConnection()
    {
        if (_disposed)
        {
            ThrowObjectDisposedException();
        }

        return new ManagedConnection(_connections.Take(), this);

        static void ThrowObjectDisposedException()
        {
            throw new ObjectDisposedException(nameof(ConnectionPool));
        }
    }

    /// <summary>
    /// Return a database connection to the pool.
    /// </summary>
    /// <param name="connection">The database connection to return.</param>
    public void Return(SQLiteDatabaseConnection connection)
    {
        if (_disposed)
        {
            connection.Dispose();
            return;
        }

        _connections.Add(connection);
    }

    /// <inheritdoc />
    public void Dispose()
    {
        if (_disposed)
        {
            return;
        }

        foreach (var connection in _connections)
        {
            connection.Dispose();
        }

        _connections.Dispose();

        _disposed = true;
    }
}