-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSQLite.ParallelExecution.cs
More file actions
60 lines (52 loc) · 1.79 KB
/
Copy pathSQLite.ParallelExecution.cs
File metadata and controls
60 lines (52 loc) · 1.79 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace DBAClientX;
public partial class SQLite
{
/// <summary>
/// Executes a collection of SQL queries concurrently using independent connections.
/// </summary>
public async Task<IReadOnlyList<object?>> RunQueriesInParallel(
IEnumerable<string> queries,
string database,
CancellationToken cancellationToken = default,
int? maxDegreeOfParallelism = null)
{
if (queries == null)
{
throw new ArgumentNullException(nameof(queries));
}
var validatedQueries = new List<string>();
var queryIndex = 0;
foreach (var query in queries)
{
if (string.IsNullOrWhiteSpace(query))
{
throw new ArgumentException($"Query at index {queryIndex} cannot be null or whitespace.", nameof(queries));
}
validatedQueries.Add(query);
queryIndex++;
}
var effectiveMaxDegreeOfParallelism = maxDegreeOfParallelism.HasValue && maxDegreeOfParallelism.Value > 0
? maxDegreeOfParallelism.Value
: DefaultMaxParallelQueries;
using var throttler = new SemaphoreSlim(effectiveMaxDegreeOfParallelism);
var tasks = validatedQueries.Select(async q =>
{
await throttler.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
return await QueryAsync(database, q, null, false, cancellationToken).ConfigureAwait(false);
}
finally
{
throttler.Release();
}
});
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
return results;
}
}