Last active
September 8, 2021 13:47
-
-
Save akunzai/895e473b37bc1d00f360a8dc6a572770 to your computer and use it in GitHub Desktop.
Fixes System.Data.SQLite Close() not releasing database file , see https://stackoverflow.com/a/38268171
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System.Collections.Generic; | |
| using System.Data; | |
| using System.Data.SQLite; | |
| using System.Linq; | |
| public static class ClearSQLiteCommandConnectionHelper | |
| { | |
| private static readonly object lockObject = new object(); | |
| private static readonly List<SQLiteCommand> OpenCommands = new List<SQLiteCommand>(); | |
| public static void Initialise() | |
| { | |
| SQLiteConnection.Changed += SqLiteConnectionOnChanged; | |
| } | |
| private static void SqLiteConnectionOnChanged(object sender, ConnectionEventArgs connectionEventArgs) | |
| { | |
| if (connectionEventArgs.EventType == SQLiteConnectionEventType.NewCommand && connectionEventArgs.Command is SQLiteCommand) | |
| { | |
| lock(lockObject) | |
| { | |
| OpenCommands.Add((SQLiteCommand) connectionEventArgs.Command); | |
| } | |
| } | |
| else if (connectionEventArgs.EventType == SQLiteConnectionEventType.DisposingCommand && connectionEventArgs.Command is SQLiteCommand) | |
| { | |
| lock(lockObject) | |
| { | |
| OpenCommands.Remove((SQLiteCommand) connectionEventArgs.Command); | |
| } | |
| } | |
| if (connectionEventArgs.EventType == SQLiteConnectionEventType.Closed) | |
| { | |
| lock(lockObject) | |
| { | |
| var commands = OpenCommands.ToList(); | |
| foreach (var cmd in commands) | |
| { | |
| if (cmd.Connection == null) | |
| { | |
| OpenCommands.Remove(cmd); | |
| } | |
| else if (cmd.Connection.State == ConnectionState.Closed) | |
| { | |
| cmd.Connection = null; | |
| OpenCommands.Remove(cmd); | |
| } | |
| } | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment