有没有一种方法可以查询主线程领域实例而不阻塞主线程?

问题描述:

领域网

我想将一些主线程领域对象传递给某些视图模型,但不想在检索它们时阻塞UI.

I'd like to pass some main-thread realm objects to some view-models, but don't want to block the UI while I retrieve them.

我需要主线程领域实例中的领域对象,以便在主线程上调用myRealmObject.PropertyChanged.如果没有后台查询,是否可以在主线程上调用后台线程领域对象的PropertyChanged?

I need realm objects from a main-thread realm instance so that myRealmObject.PropertyChanged is called on the main thread. If no background query, is there a way to make a background-thread realm object's PropertyChanged be called on the main thread?

您可以在后台线程上查询并创建一个ThreadSafeReference,您可以将其传递给您的VM.例如:

You can query on a background thread and create a ThreadSafeReference that you can pass to your VMs. For example:

var reference = await Task.Run(() =>
{
    using (var realm = Realm.GetInstance())
    {
        var modelToPass = realm.All<MyModel>().Where(...).FirstOrDefault();
        return ThreadSafeReference.Create(modelToPass);
    }
});
// Pass reference to your ViewModel

然后在您的ViewModel中可以拥有

Then in your ViewModel you can have

public void Initialize(ThreadSafeReference.Object<MyModel> reference)
{
    var realm = Realm.GetInstance();
    var myModel = realm.ResolveReference(reference);
    // Do stuff with myModel - it's a main thread reference to
    // the model you resolved on the background thread
}

查看文档了解更多详细说明