Skip to content

Commit

Permalink
Make pooled connections weak
Browse files Browse the repository at this point in the history
This allows connections to be Disposed when not in use.
  • Loading branch information
praeclarum committed Jan 25, 2019
1 parent efd63a2 commit ca1c06b
Showing 1 changed file with 26 additions and 17 deletions.
43 changes: 26 additions & 17 deletions src/SQLiteAsync.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1311,23 +1311,39 @@ class SQLiteConnectionPool
{
class Entry
{
public SQLiteConnectionString ConnectionString { get; private set; }
public SQLiteConnectionWithLock Connection { get; private set; }
WeakReference<SQLiteConnectionWithLock> connection;

public SQLiteConnectionString ConnectionString { get; }

public Entry (SQLiteConnectionString connectionString)
{
ConnectionString = connectionString;
Connection = new SQLiteConnectionWithLock (connectionString);
}

public SQLiteConnectionWithLock Connect ()
{
SQLiteConnectionWithLock c = null;
var wc = connection;
if (wc == null || !wc.TryGetTarget (out c)) {
c = new SQLiteConnectionWithLock (ConnectionString);

// If the database is FullMutex, then we don't need to bother locking
if (ConnectionString.OpenFlags.HasFlag (SQLiteOpenFlags.FullMutex)) {
c.SkipLock = true;
}

connection = new WeakReference<SQLiteConnectionWithLock> (c);
}
return c;
}

public void Close ()
{
if (Connection == null)
return;
using (var l = Connection.Lock ()) {
Connection.Dispose ();
var wc = connection;
if (wc != null && wc.TryGetTarget (out var c)) {
c.Close ();
}
Connection = null;
connection = null;
}
}

Expand All @@ -1347,22 +1363,15 @@ public static SQLiteConnectionPool Shared {

public SQLiteConnectionWithLock GetConnection (SQLiteConnectionString connectionString)
{
Entry entry;
lock (_entriesLock) {
Entry entry;
string key = connectionString.ConnectionString;

if (!_entries.TryGetValue (key, out entry)) {
entry = new Entry (connectionString);
_entries[key] = entry;
}

// If the database is FullMutex, then we don't need to bother locking
if (connectionString.OpenFlags.HasFlag (SQLiteOpenFlags.FullMutex)) {
entry.Connection.SkipLock = true;
}

return entry.Connection;
}
return entry.Connect ();
}

public void CloseConnection (SQLiteConnectionString connectionString)
Expand Down

0 comments on commit ca1c06b

Please sign in to comment.