【问题标题】:Deboucing async property refresh去抖动异步属性刷新
【发布时间】:2019-06-05 14:06:00
【问题描述】:

感谢您对以下问题的帮助: A 在我的班级中有一个财产可以说

string Foo {get;set;}

类中有刷新功能。有一个长时间运行的方法,其中更新了

Foo = await Task.Run()... etc. 

当每秒调用 1000 次刷新时,如何避免堆叠 Task-s?去抖?节流?怎么做? Rx 在项目中可用,我使用的是 dotnet core 2.2。

类构造函数


    res = Observable.FromAsync(() => Task.Run(async () =>
    {
                       await Task.Delay(5000);
                       return "Example";
    }
    )).Throttle(TimeSpan.FromSeconds(10));


    private IObservable<string> res;

    public string Foo
    {
                get => _foo;
                set
                {
                    this.RaiseAndSetIfChanged(ref _foo, value);
                }
    }

    public void RefreshFoo()
    {
                res.Subscribe(x => Foo = x);
    }

【问题讨论】:

  • 主要问题是每次调用RefreshFoo 时都会创建新订阅。如果 RefreshFoo 被称为“每秒 1000 次”,您期望什么输出?

标签: c# system.reactive throttling debouncing


【解决方案1】:

如果您可以使用其他软件包,我建议您使用 ReactiveUI,它是 ReactiveCommand,它将立即处理您的所有问题:

  var command = ReactiveCommand.CreateFromTask(async () =>
            { // define the work
                Console.WriteLine("Executing at " + DateTime.Now);
                await Task.Delay(1000);
                return "test";
            });

            command.Subscribe(res => {
                // do something with the result: assign to property
            });

            var d = Observable.Interval(TimeSpan.FromMilliseconds(500), RxApp.TaskpoolScheduler) // you can specify scheduler if you want
                .Do(_ => Console.WriteLine("Invoking at " + DateTime.Now))
                .Select(x => Unit.Default) // command argument type is Unit
                .InvokeCommand(command); // this checks command.CanExecute which is false while it is executing

输出:

Invoking at 2019-01-22 13:34:04
Executing at 2019-01-22 13:34:04
Invoking at 2019-01-22 13:34:05
Invoking at 2019-01-22 13:34:05
Executing at 2019-01-22 13:34:05

我知道这个包主要用于 UI 开发,但没有什么好技巧,比如你可以在任何地方使用的 ReactiveCommand。

注意await command.Execute()默认不检查是否可以执行命令。

我认为这比您的解决方案更具可读性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-15
    • 2020-01-23
    • 2020-02-22
    • 2023-03-12
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    相关资源
    最近更新 更多