代码:
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);
}
}在功能上等同于:
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
<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
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);
});
}
}
}发布于 2020-01-17 05:03:51
您正在使用的ToProperty重载具有反射开销。试试ToProperty(this, nameof(Score))。可能仍然会影响性能,因为ToProperty所做的比您发布的功能等价的功能要多一点。
https://stackoverflow.com/questions/59776483
复制相似问题