有没有一种方法可以查询主线程领域实例而不阻塞主线程? [英] Is there a way to query a main-thread realm instance without blocking the main thread?

查看:68
本文介绍了有没有一种方法可以查询主线程领域实例而不阻塞主线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

领域网

我想将一些主线程领域对象传递给某些视图模型,但不想在检索它们时阻塞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
}

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

这篇关于有没有一种方法可以查询主线程领域实例而不阻塞主线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆