Skip to content

Commit ca1c06b

Browse files
committed
Make pooled connections weak
This allows connections to be Disposed when not in use.
1 parent efd63a2 commit ca1c06b

File tree

1 file changed

+26
-17
lines changed

1 file changed

+26
-17
lines changed

src/SQLiteAsync.cs

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1311,23 +1311,39 @@ class SQLiteConnectionPool
13111311
{
13121312
class Entry
13131313
{
1314-
public SQLiteConnectionString ConnectionString { get; private set; }
1315-
public SQLiteConnectionWithLock Connection { get; private set; }
1314+
WeakReference<SQLiteConnectionWithLock> connection;
1315+
1316+
public SQLiteConnectionString ConnectionString { get; }
13161317

13171318
public Entry (SQLiteConnectionString connectionString)
13181319
{
13191320
ConnectionString = connectionString;
1320-
Connection = new SQLiteConnectionWithLock (connectionString);
1321+
}
1322+
1323+
public SQLiteConnectionWithLock Connect ()
1324+
{
1325+
SQLiteConnectionWithLock c = null;
1326+
var wc = connection;
1327+
if (wc == null || !wc.TryGetTarget (out c)) {
1328+
c = new SQLiteConnectionWithLock (ConnectionString);
1329+
1330+
// If the database is FullMutex, then we don't need to bother locking
1331+
if (ConnectionString.OpenFlags.HasFlag (SQLiteOpenFlags.FullMutex)) {
1332+
c.SkipLock = true;
1333+
}
1334+
1335+
connection = new WeakReference<SQLiteConnectionWithLock> (c);
1336+
}
1337+
return c;
13211338
}
13221339

13231340
public void Close ()
13241341
{
1325-
if (Connection == null)
1326-
return;
1327-
using (var l = Connection.Lock ()) {
1328-
Connection.Dispose ();
1342+
var wc = connection;
1343+
if (wc != null && wc.TryGetTarget (out var c)) {
1344+
c.Close ();
13291345
}
1330-
Connection = null;
1346+
connection = null;
13311347
}
13321348
}
13331349

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

13481364
public SQLiteConnectionWithLock GetConnection (SQLiteConnectionString connectionString)
13491365
{
1366+
Entry entry;
13501367
lock (_entriesLock) {
1351-
Entry entry;
13521368
string key = connectionString.ConnectionString;
1353-
13541369
if (!_entries.TryGetValue (key, out entry)) {
13551370
entry = new Entry (connectionString);
13561371
_entries[key] = entry;
13571372
}
1358-
1359-
// If the database is FullMutex, then we don't need to bother locking
1360-
if (connectionString.OpenFlags.HasFlag (SQLiteOpenFlags.FullMutex)) {
1361-
entry.Connection.SkipLock = true;
1362-
}
1363-
1364-
return entry.Connection;
13651373
}
1374+
return entry.Connect ();
13661375
}
13671376

13681377
public void CloseConnection (SQLiteConnectionString connectionString)

0 commit comments

Comments
 (0)