Browse Source

Change database init to Lazy to be thread safe

pull/324/head
Ionite 12 months ago
parent
commit
20d8a065f0
No known key found for this signature in database
  1. 12
      StabilityMatrix.Core/Database/LiteDbContext.cs

12
StabilityMatrix.Core/Database/LiteDbContext.cs

@ -16,8 +16,8 @@ public class LiteDbContext : ILiteDbContext
private readonly ISettingsManager settingsManager; private readonly ISettingsManager settingsManager;
private readonly DebugOptions debugOptions; private readonly DebugOptions debugOptions;
private LiteDatabaseAsync? database; private readonly Lazy<LiteDatabaseAsync> lazyDatabase;
public LiteDatabaseAsync Database => database ??= CreateDatabase(); public LiteDatabaseAsync Database => lazyDatabase.Value;
// Notification events // Notification events
public event EventHandler? CivitModelsChanged; public event EventHandler? CivitModelsChanged;
@ -46,6 +46,8 @@ public class LiteDbContext : ILiteDbContext
this.logger = logger; this.logger = logger;
this.settingsManager = settingsManager; this.settingsManager = settingsManager;
this.debugOptions = debugOptions.Value; this.debugOptions = debugOptions.Value;
lazyDatabase = new Lazy<LiteDatabaseAsync>(CreateDatabase);
} }
private LiteDatabaseAsync CreateDatabase() private LiteDatabaseAsync CreateDatabase()
@ -164,11 +166,11 @@ public class LiteDbContext : ILiteDbContext
public void Dispose() public void Dispose()
{ {
if (database is not null) if (lazyDatabase.IsValueCreated)
{ {
try try
{ {
database.Dispose(); Database.Dispose();
} }
catch (ObjectDisposedException) { } catch (ObjectDisposedException) { }
catch (ApplicationException) catch (ApplicationException)
@ -176,8 +178,6 @@ public class LiteDbContext : ILiteDbContext
// Ignores a mutex error from library // Ignores a mutex error from library
// https://stability-matrix.sentry.io/share/issue/5c62f37462444e7eab18cea314af231f/ // https://stability-matrix.sentry.io/share/issue/5c62f37462444e7eab18cea314af231f/
} }
database = null;
} }
GC.SuppressFinalize(this); GC.SuppressFinalize(this);

Loading…
Cancel
Save