Use Realm in a Console App - .NET SDK
Overview
Realm instances and objects are bound to a
SynchronizationContext,
which means that they can only be accessed on the same thread on which they
are created. On platforms with a UI thread, the framework installs a
SynchronizationContext
on the main thread, allowing you to make reads and
writes to the database with asynchronous calls.
However, in console apps, there is no UI thread, and thus no
SynchronizationContext
installed. This means that if you await
an
asynchronous Task, a random thread is spun up from the thread pool, from which
you can no longer access any previously-opened Realm instances.
To be able to efficiently use Realm between asynchronous calls, you should
install a SynchronizationContext
- either one you implement yourself, or one
provided in a 3rd party library.
Usage
The following code example uses the Realm SDK to
add Device Sync to a console application. The app
uses the third-party Nito.AsyncEx
package to provide an AsyncContext
. The Realm code is then run under the
AsyncContext
.
using System; using System.Linq; using System.Threading.Tasks; using Nito.AsyncEx; using Realms; using Realms.Sync; namespace ConsoleTests { class Program { const string myRealmAppId = "myAppId"; public static void Main(string[] args) { Nito.AsyncEx.AsyncContext.Run(async () => await MainAsync(args)); } private static async Task MainAsync(string[] args) { var app = App.Create(myRealmAppId); var user = await app.LogInAsync(Credentials.Anonymous()); var config = new PartitionSyncConfiguration("partition", user); using var realm = await Realm.GetInstanceAsync(); var itemsBiggerThanFive = realm.All<Item>().Where(f => f.Size > 5); foreach (var item in itemsBiggerThanFive) { await Task.Delay(10); // Simulates some background work Console.WriteLine(item.Size); } }