Navigation

Use Realm in a Console App - .NET SDK

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.

In the following example, we have built a console app that uses the third-party Nito.AsyncEx package to provide an AsyncContext, under which we run our realm code:

public static void Main(string[] args)
{
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 SyncConfiguration("partition", user);
using var realm = await Realm.GetInstanceAsync();
var foos = realm.All<Foo>().Where(f => f.Bar > 5);
foreach (var foo in foos)
{
await Task.Delay(10); // Simulates some background work
Console.WriteLine(foo.Bar);
}
}
Give Feedback