Realm .NET 无法从另一个线程访问领域对象

Realm .NET can't access a realmobject from another thread

根据回答,我发现我不能从另一个线程访问领域对象,但是从回答中,我了解到我可以存储领域对象的引用然后使用它在另一个线程中。

我想循环它直到它被插入,但问题是我无法在另一个线程上访问 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;
            });
        }
    }
}

答案说您可以存储对对象 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;
        });
    }
}