using Microsoft.Data.Sqlite; namespace Febe.Data; /// /// Keeps the commands that creates on this thread while a read runs, and disposes them when the /// read ends. Reads build their commands inline (c.Command(...).ExecuteReader()); left to the garbage collector, /// a command keeps its SQLite statement alive until the finalizer runs, so the connection closed by /// would only really close then, keeping the files open (#46). /// internal sealed class CommandScope : IDisposable { [ThreadStatic] private static CommandScope? t_current; private readonly CommandScope? _outer; private readonly List _commands = []; private CommandScope(CommandScope? outer) => _outer = outer; /// Starts tracking the commands created on this thread until the scope is disposed. public static CommandScope Begin() => t_current = new CommandScope(t_current); /// Adds to the open scope of this thread, if any. public static void Track(SqliteCommand command) => t_current?._commands.Add(command); public void Dispose() { t_current = _outer; foreach (var command in _commands) { command.Dispose(); } _commands.Clear(); } }