【问题标题】:Realm .NET can't access a realmobject from another threadRealm .NET 无法从另一个线程访问领域对象
【发布时间】:2021-03-01 17:01:32
【问题描述】:

基于this 答案,我发现我无法从另一个线程访问领域对象,但从答案中,我了解到我可以存储领域对象的引用,然后在另一个线程中使用它。

我想循环它直到它被插入,但问题是我无法访问另一个线程上的var documentvar s。 那么我该如何找到解决该问题的方法呢?

private async void UpdateNotifications_OnAdd(object sender, EventArgs e)
{
    //UpdateNotification is my RealmObject
    var s = (UpdateNotifications)sender;
    //Here I want to find the document that has the id from my updateNotification
    var document = realm.Find<Document>(s.Identifier)

    await Task.Run(async () =>
    {
        while(!s.Inserted)
        {
            //Here I want to access my document and my S
            string text = queryFinder(document)
            realm.Write(() =>
            {
                s.Inserted = true;
            });
        }
    }
}

【问题讨论】:

    标签: c# realm


    【解决方案1】:

    答案说您可以存储对对象 Id 的引用,然后在后台线程上重新查询(使用 realm.Find)。虽然它有点旧,但今天有更好的方法 - 使用ThreadSafeReference。话虽如此,您的代码将无法工作,因为您在后台线程上使用主线程中的 Realm 实例,这也是不允许的。您需要对其进行一些重构,使其看起来像这样:

    private async void UpdateNotifications_OnAdd(object sender, EventArgs e)
    {
        var notifications = (UpdateNotifications)sender;
        var document = realm.Find<Document>(notifications.Identifier);
    
        // Create thread safe references to notifications and document.
        // We'll use them to look up the objects in the background.
        var notificationsRef = ThreadSafeReference.Create(notifications);
        var documentRef = ThreadSafeReference.Create(document);
    
        await Task.Run(async () =>
        {
            // Always dispose of the Realm on a background thread
            using bgRealm = Realm.GetInstance();
    
            // We need to look up the notifications and document objects
            // on the background thread from the references we created
            var bgNotifications = bgRealm.Resolve(notificationsRef);
            var bgDocument = bgRealm.Resolve(documentRef;)
    
            string text = queryFinder(bgDocument);
            bgRealm.Write(() =>
            {
                bgNotifications.Inserted = true;
            });
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-11
      • 1970-01-01
      • 1970-01-01
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多