From 0c9eb3ad61a412f6ebed4d0dc08f593743cee8d1 Mon Sep 17 00:00:00 2001 From: Dean Herbert Date: Fri, 21 Jan 2022 01:33:45 +0900 Subject: [PATCH] Add realm factory helper methods to run work on the correct context Avoids constructing a new `Realm` instance when called from the update thread without worrying about disposal. --- osu.Game/Database/RealmContextFactory.cs | 35 ++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/osu.Game/Database/RealmContextFactory.cs b/osu.Game/Database/RealmContextFactory.cs index 31dbb0c6c4..50e456a0c8 100644 --- a/osu.Game/Database/RealmContextFactory.cs +++ b/osu.Game/Database/RealmContextFactory.cs @@ -169,6 +169,41 @@ namespace osu.Game.Database /// public bool Compact() => Realm.Compact(getConfiguration()); + /// + /// Run work on realm with a return value. + /// + /// + /// Handles correct context management automatically. + /// + /// The work to run. + /// The return type. + public T Run(Func action) + { + if (ThreadSafety.IsUpdateThread) + return action(Context); + + using (var realm = CreateContext()) + return action(realm); + } + + /// + /// Run work on realm. + /// + /// + /// Handles correct context management automatically. + /// + /// The work to run. + public void Run(Action action) + { + if (ThreadSafety.IsUpdateThread) + action(Context); + else + { + using (var realm = CreateContext()) + action(realm); + } + } + public Realm CreateContext() { if (isDisposed)