Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
Kit de desarrollo de software .NET

Use Realm in a Console App - .NET SDK

Las instancias y los objetos del reino están vinculados a un Contexto de sincronización, lo que significa que solo se puede acceder a ellos en el mismo hilo en el que se crearon. En plataformas con un hilo de interfaz de usuario, el framework instala un SynchronizationContext en el hilo principal, lo que le permite realizar lecturas y escrituras en la base de datos con llamadas asincrónicas.

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.

El siguiente ejemplo de código utiliza el SDK de Realm para añadir Device Sync a una aplicación de consola. La aplicación utiliza el paquete Nito.AsyncEx de terceros para proporcionar un AsyncContext. El código de Realm se ejecuta luego bajo el 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);
}
}

Volver

Partition-Based Sync

En esta página