Skip to content

Commit 08dd84d

Browse files
committed
Add WithAllReaders
1 parent 64ed444 commit 08dd84d

1 file changed

Lines changed: 37 additions & 10 deletions

File tree

PowerSync/PowerSync.Common/MDSQLite/MDSQLiteAdapter.cs

Lines changed: 37 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -152,9 +152,11 @@ protected virtual void LoadExtension(SqliteConnection db)
152152
try { tablesUpdatedTask?.Wait(2000); } catch { /* expected */ }
153153
base.Close();
154154
writeConnection?.Close();
155-
var readConnections = await LockReaders();
155+
await WithAllReaders((connections) =>
156+
{
157+
foreach (var conn in connections) conn.Close();
158+
});
156159
readPool.Writer.Complete();
157-
foreach (var conn in readConnections) conn.Close();
158160
}
159161

160162
public async Task<NonQueryResult> Execute(string query, object?[]? parameters = null)
@@ -301,26 +303,51 @@ public async Task RefreshSchema()
301303
{
302304
await initialized;
303305
await writeConnection.RefreshSchema();
304-
var connections = await LockReaders();
305-
foreach (var conn in connections) await conn.RefreshSchema();
306-
UnlockReaders(connections);
306+
await WithAllReaders(async (connections) =>
307+
{
308+
foreach (var conn in connections) await conn.RefreshSchema();
309+
});
307310
}
308311

309-
private async Task<List<MDSQLiteConnection>> LockReaders()
312+
private async Task WithAllReaders(Func<List<MDSQLiteConnection>, Task> callback)
310313
{
311314
var connections = new List<MDSQLiteConnection>(resolvedOptions.ReadPoolSize);
312315
for (int i = 0; i < resolvedOptions.ReadPoolSize; i++)
313316
{
314317
connections.Add(await readPool.Reader.ReadAsync());
315318
}
316-
return connections;
319+
320+
try
321+
{
322+
await callback(connections);
323+
}
324+
finally
325+
{
326+
foreach (var conn in connections)
327+
{
328+
readPool.Writer.TryWrite(conn);
329+
}
330+
}
317331
}
318332

319-
private void UnlockReaders(List<MDSQLiteConnection> connections)
333+
private async Task WithAllReaders(Action<List<MDSQLiteConnection>> callback)
320334
{
321-
foreach (var conn in connections)
335+
var connections = new List<MDSQLiteConnection>(resolvedOptions.ReadPoolSize);
336+
for (int i = 0; i < resolvedOptions.ReadPoolSize; i++)
322337
{
323-
readPool.Writer.TryWrite(conn);
338+
connections.Add(await readPool.Reader.ReadAsync());
339+
}
340+
341+
try
342+
{
343+
callback(connections);
344+
}
345+
finally
346+
{
347+
foreach (var conn in connections)
348+
{
349+
readPool.Writer.TryWrite(conn);
350+
}
324351
}
325352
}
326353
}

0 commit comments

Comments
 (0)