【问题标题】:Listening to PropertyChanged event on main thread, for changes done in background threads在主线程上侦听 PropertyChanged 事件,以了解在后台线程中完成的更改
【发布时间】:2016-11-29 15:25:44
【问题描述】:

不确定这是否可能,但我浏览了文档,它给我的印象是领域是围绕这种东西构建的。我正在尝试监听在后台线程中对领域对象所做的更改。

下面列出的代码将向领域添加一个 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
        });
    }
});

【问题讨论】:

    标签: ios multithreading xamarin xamarin.ios realm


    【解决方案1】:

    This was recently implemented in the .NET SDK,因此您的代码应该可以在 Realm Xamarin 的下一个版本中正常运行。

    【讨论】:

    • 知道计划什么时候发布吗?
    • 我们通常避免给出具体日期,因为这些日期总是会发生变化,而是更喜欢使用soon™。话虽如此,我们对在假期前发布新版本持乐观态度。如果您觉得现在迫不及待想要它,您可以随时从source 构建。
    • 我明白你的意思我实际上是在 nuget 上寻找一个 beta 频道,不知道我可以使用这些资源来获取尚未发布的代码。试试看,谢谢回复
    • 我们现在已经发布了Realm 0.81.0,其中包括对它的支持。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 2016-11-15
    • 2011-09-06
    • 2013-12-10
    相关资源
    最近更新 更多