Reputation: 1003
Based on this answer, I find out that I can't access a realm object from another thread, but from the answer, I understood that I can store the reference of the realmobject and then use it inside another thread.
I want to loop it until it's inserted but the problem is that I can't access the var document
and var s
on another thread.
How then I can find a workaround for that problem?
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;
});
}
}
}
Upvotes: 1
Views: 321
Reputation: 2186
The answer says you can store a reference to the Id of the object then requery that (use realm.Find
) on the background thread. It is a bit old though and there's a better way to do it today - using a ThreadSafeReference
. That being said, your code won't work because you are using a Realm instance from the main thread on a background thread, which is also disallowed. You would need to refactor it a little so that it kinda looks like this:
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;
});
}
}
Upvotes: 3