Merge pull request #18790 from peppy/fix-realm-async-write-blocking-overhead

Fix blocking overhead when calling `WriteAsync`
This commit is contained in:
Dean Herbert 2022-06-22 09:39:17 +09:00 committed by GitHub
commit cf0f32f928
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 15 additions and 4 deletions

View File

@ -385,11 +385,22 @@ public void Write(Action<Realm> action)
/// Write changes to realm asynchronously, guaranteeing order of execution. /// Write changes to realm asynchronously, guaranteeing order of execution.
/// </summary> /// </summary>
/// <param name="action">The work to run.</param> /// <param name="action">The work to run.</param>
public async Task WriteAsync(Action<Realm> action) public Task WriteAsync(Action<Realm> action)
{
// Regardless of calling Realm.GetInstance or Realm.GetInstanceAsync, there is a blocking overhead on retrieval.
// Adding a forced Task.Run resolves this.
return Task.Run(async () =>
{ {
total_writes_async.Value++; total_writes_async.Value++;
// Not attempting to use Realm.GetInstanceAsync as there's seemingly no benefit to us (for now) and it adds complexity due to locking
// concerns in getRealmInstance(). On a quick check, it looks to be more suited to cases where realm is connecting to an online sync
// server, which we don't use. May want to report upstream or revisit in the future.
using (var realm = getRealmInstance()) using (var realm = getRealmInstance())
// ReSharper disable once AccessToDisposedClosure (WriteAsync should be marked as [InstantHandle]).
await realm.WriteAsync(() => action(realm)); await realm.WriteAsync(() => action(realm));
});
} }
/// <summary> /// <summary>