Overview
Realm instances and objects are bound to aSynchronizationContext,which means that they can only be accessed on the same thread on which theyare created. On platforms with a UI thread, the framework installs aSynchronizationContext on the main thread, allowing you to make reads andwrites to the database with asynchronous calls.
However, in console apps, there is no UI thread, and thus noSynchronizationContext installed. This means that if youawait anasynchronous Task, a random thread is spun up from the thread pool, from whichyou can no longer access any previously-opened Realm instances.
To be able to efficiently use Realm between asynchronous calls, you shouldinstall aSynchronizationContext - either one you implement yourself, or oneprovided in a 3rd party library.
Usage
The following code example uses the Realm SDK toadd Device Sync to a console application. The appuses the third-partyNito.AsyncExpackage to provide anAsyncContext. The Realm code is then run under theAsyncContext.
using System; using System.Linq; using System.Threading.Tasks; using Nito.AsyncEx; using Realms; using Realms.Sync; namespaceConsoleTests { classProgram { conststring myRealmAppId ="myAppId"; publicstaticvoidMain(string[] args) { Nito.AsyncEx.AsyncContext.Run(async () =>await MainAsync(args)); } privatestaticasync TaskMainAsync(string[] args) { var app = App.Create(myRealmAppId); var user =await app.LogInAsync(Credentials.Anonymous()); var config =new PartitionSyncConfiguration("partition", user); usingvar realm =await Realm.GetInstanceAsync(); var itemsBiggerThanFive = realm.All<Item>().Where(f => f.Size >5); foreach (var itemin itemsBiggerThanFive) { await Task.Delay(10);// Simulates some backgroundwork Console.WriteLine(item.Size); } }