Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[release/7.0] Move taking of lock earlier to avoid race in PruneCallback #30098

Merged
merged 2 commits into from
Feb 7, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 66 additions & 20 deletions src/Microsoft.Data.Sqlite.Core/SqliteConnectionFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ namespace Microsoft.Data.Sqlite
{
internal class SqliteConnectionFactory
{
private static readonly bool QuirkEnabled29952
= AppContext.TryGetSwitch("Microsoft.EntityFrameworkCore.Issue29952", out var enabled) && enabled;

public static readonly SqliteConnectionFactory Instance = new();

#pragma warning disable IDE0052 // Remove unread private members
Expand Down Expand Up @@ -138,40 +141,83 @@ private void PruneCallback(object? _)
}
}

for (var i = _idlePoolGroups.Count - 1; i >= 0; i--)
if (QuirkEnabled29952)
{
var poolGroup = _idlePoolGroups[i];
for (var i = _idlePoolGroups.Count - 1; i >= 0; i--)
{
var poolGroup = _idlePoolGroups[i];

if (!poolGroup.Clear())
{
_idlePoolGroups.Remove(poolGroup);
}
}

_lock.EnterWriteLock();

try
{
var activePoolGroups = new Dictionary<string, SqliteConnectionPoolGroup>();
foreach (var entry in _poolGroups)
{
var poolGroup = entry.Value;

if (!poolGroup.Clear())
if (poolGroup.Prune())
{
_idlePoolGroups.Add(poolGroup);
}
else
{
activePoolGroups.Add(entry.Key, poolGroup);
}
}

_poolGroups = activePoolGroups;
}
finally
{
_idlePoolGroups.Remove(poolGroup);
_lock.ExitWriteLock();
}
}

_lock.EnterWriteLock();

try
else
{
var activePoolGroups = new Dictionary<string, SqliteConnectionPoolGroup>();
foreach (var entry in _poolGroups)
_lock.EnterWriteLock();

try
{
var poolGroup = entry.Value;

if (poolGroup.Prune())
for (var i = _idlePoolGroups.Count - 1; i >= 0; i--)
{
_idlePoolGroups.Add(poolGroup);
var poolGroup = _idlePoolGroups[i];

if (!poolGroup.Clear())
{
_idlePoolGroups.Remove(poolGroup);
}
}
else

var activePoolGroups = new Dictionary<string, SqliteConnectionPoolGroup>();
foreach (var entry in _poolGroups)
{
activePoolGroups.Add(entry.Key, poolGroup);
var poolGroup = entry.Value;

if (poolGroup.Prune())
{
_idlePoolGroups.Add(poolGroup);
}
else
{
activePoolGroups.Add(entry.Key, poolGroup);
}
}
}

_poolGroups = activePoolGroups;
}
finally
{
_lock.ExitWriteLock();
_poolGroups = activePoolGroups;
}
finally
{
_lock.ExitWriteLock();
}
}
}
}
Expand Down