有没有办法在不阻塞主线程的情况下查询主线程域实例?

时间:2017-12-31 03:06:02

标签: c# realm

境界-DOTNET

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

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

1 个答案:

答案 0 :(得分:2)

您可以在后台线程上查询并创建一个可以传递给VM的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以获取更详细的说明。