首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ReactiveUI ObservableAsPropertyHelper性能

ReactiveUI ObservableAsPropertyHelper性能
EN

Stack Overflow用户
提问于 2020-01-17 03:23:26
回答 1查看 266关注 0票数 0

代码:

代码语言:javascript
复制
public class AppViewModel : ReactiveObject
{
    public AppViewModel()
    {
        Observable.Timer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), RxApp.MainThreadScheduler)
        .Do(_ => Score++)
        .Subscribe();
    }

    private long _score;
    public long Score
    {
        get => _score;
        set => this.RaiseAndSetIfChanged(ref _score, value);
    }
}

在功能上等同于:

代码语言:javascript
复制
public class AppViewModel : ReactiveObject
{
    private readonly ObservableAsPropertyHelper<long> _score;

    public AppViewModel()
    {
        _score =
            Observable
            .Timer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), RxApp.MainThreadScheduler)
            .ToProperty(this, x => x.Score);
    }

    public long Score => _score.Value;
}

虽然,在第二种情况下,在开始计数之前有一个明显的延迟(在我的机器上超过一秒)。导致这种情况的原因是什么?

为了完整性:

MainWindow.xaml

代码语言:javascript
复制
<reactiveui:ReactiveWindow 
    x:Class="ReactiveDemo.MainWindow"
    x:TypeArguments="reactivedemo:AppViewModel"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:reactivedemo="clr-namespace:ReactiveDemo"
    xmlns:reactiveui="http://reactiveui.net"
    Title="Rx" Height="450" Width="800"
    mc:Ignorable="d">
    <Viewbox>
        <Label x:Name="ScoreLabel" ContentStringFormat="D2" FontFamily="Lucida Console" />
    </Viewbox>
</reactiveui:ReactiveWindow>

MainWindow.xaml.cs

代码语言:javascript
复制
using ReactiveUI;
using System.Reactive.Disposables;

namespace ReactiveDemo
{
    public partial class MainWindow : ReactiveWindow<AppViewModel>
    {
        public MainWindow()
        {
            InitializeComponent();

            ViewModel = new AppViewModel();

            this.WhenActivated(disposableRegistration =>
            {
                this.OneWayBind(ViewModel,
                    viewModel => viewModel.Score,
                    view => view.ScoreLabel.Content)
                    .DisposeWith(disposableRegistration);
            });
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2020-01-17 05:03:51

您正在使用的ToProperty重载具有反射开销。试试ToProperty(this, nameof(Score))。可能仍然会影响性能,因为ToProperty所做的比您发布的功能等价的功能要多一点。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59776483

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档