在主线程上侦听PropertyChanged事件,以便在后台线程中完成更改

时间:2016-11-29 15:25:45

标签: ios multithreading xamarin xamarin.ios realm

不确定这是否可行,但是我通过文档给了我的印象,即领域是围绕这种事情构建的。我正在尝试侦听在后台线程中执行的对realm对象所做的更改。

下面列出的代码会将Post对象添加到领域,读取对象并听取它的属性更改事件。当我直接更新该对象时,会引发该事件。但是当我在另一个线程上读取对象并更新它时,我希望主线程上的对象能够获得更新,但事实并非如此。我错过了什么吗?

var realm = Realm.GetInstance();
string newPostID = Guid.NewGuid().ToString();

realm.Write(() => {
var newPost = realm.CreateObject<Post>();
    newPost.ID = newPostID;
    newPost.Count = 0;
});

var post = realm.All<Post>().Where(item => item.ID == newPostID).FirstOrDefault();
post.PropertyChanged += (object sender, PropertyChangedEventArgs e) =>
{
    // Changed
};

Realm.GetInstance().Write(() =>
{
    var threadPost = Realm.GetInstance().All<Post>().Where(item => item.ID == newPostID).FirstOrDefault();

    threadPost.Count++;
    // This will trigger the PropertyChanged event
});

Task.Run(() => {
    for (int i = 0; i < 5; i++)
    {
        System.Threading.Thread.Sleep(500);

        Realm.GetInstance().Write(() =>
        {
            var threadPost = Realm.GetInstance().All<Post>().Where(item => item.ID == newPostID).FirstOrDefault();

            threadPost.Count++;
            // This will not trigger the PropertyChanged event on the main thread
        });
    }
});

1 个答案:

答案 0 :(得分:0)

This was recently implemented in the .NET SDK,因此您的代码应该按照您对Realm Xamarin的下一个版本的预期工作。