【问题标题】:Is there a way to query a main-thread realm instance without blocking the main thread?有没有办法在不阻塞主线程的情况下查询主线程领域实例?
【发布时间】:2017-12-31 03:06:02
【问题描述】:

领域点网

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

我需要来自主线程领域实例的领域对象,以便在主线程上调用 myRealmObject.PropertyChanged。如果没有后台查询,有没有办法让后台线程领域对象的 PropertyChanged 在主线程上被调用?

【问题讨论】:

    标签: c# realm


    【解决方案1】:

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

    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 中你可以拥有

    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
    }
    

    查看the docs了解更详细的说明。

    【讨论】:

    • 感谢您的及时答复!性能方面,对大量引用调用 ResolveReference (可测量地)是否比只为它们查询一次主线程领域更快?
    • 取决于您的查询类型 - 如果您只是通过 PK 查找对象,那么不会。如果您正在进行复杂的查找,这可能涉及表扫描(例如,按字符串包含或类似内容进行搜索),那么可以。粗略地说,ResolveReference 具有与 PK 查找类似的性能,但它的好处是即使对于没有主键的对象也可用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    相关资源
    最近更新 更多