From 20d8a065f0a2a4e60cecde5715f511e4aa65c99a Mon Sep 17 00:00:00 2001 From: Ionite Date: Wed, 6 Dec 2023 16:53:55 -0500 Subject: [PATCH] Change database init to Lazy to be thread safe --- StabilityMatrix.Core/Database/LiteDbContext.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/StabilityMatrix.Core/Database/LiteDbContext.cs b/StabilityMatrix.Core/Database/LiteDbContext.cs index 2fad7570..429c092b 100644 --- a/StabilityMatrix.Core/Database/LiteDbContext.cs +++ b/StabilityMatrix.Core/Database/LiteDbContext.cs @@ -16,8 +16,8 @@ public class LiteDbContext : ILiteDbContext private readonly ISettingsManager settingsManager; private readonly DebugOptions debugOptions; - private LiteDatabaseAsync? database; - public LiteDatabaseAsync Database => database ??= CreateDatabase(); + private readonly Lazy lazyDatabase; + public LiteDatabaseAsync Database => lazyDatabase.Value; // Notification events public event EventHandler? CivitModelsChanged; @@ -46,6 +46,8 @@ public class LiteDbContext : ILiteDbContext this.logger = logger; this.settingsManager = settingsManager; this.debugOptions = debugOptions.Value; + + lazyDatabase = new Lazy(CreateDatabase); } private LiteDatabaseAsync CreateDatabase() @@ -164,11 +166,11 @@ public class LiteDbContext : ILiteDbContext public void Dispose() { - if (database is not null) + if (lazyDatabase.IsValueCreated) { try { - database.Dispose(); + Database.Dispose(); } catch (ObjectDisposedException) { } catch (ApplicationException) @@ -176,8 +178,6 @@ public class LiteDbContext : ILiteDbContext // Ignores a mutex error from library // https://stability-matrix.sentry.io/share/issue/5c62f37462444e7eab18cea314af231f/ } - - database = null; } GC.SuppressFinalize(this);