ReactiveCommand.CreateAsync task.如何使用按钮取消任务

本文关键字:按钮 取消 任务 何使用 CreateAsync task ReactiveCommand | 更新日期: 2023-09-27 18:36:09

我有这个反应命令;

LoadFileCommand = ReactiveCommand.CreateAsyncTask((_, cancellationToken) => LoadFile(cancellationToken));

我也订阅了命令

subscription = LoadFileCommand.Subscribe(file => OnFileLoaded(file);

现在我想从 UI(在按钮中)发出另一个命令来取消任务。

但是怎么做呢?

我没有办法将我的取消令牌"注入"到加载文件命令中。我真的迷路了!

编辑:

目前,在我的 MainViewModel 下.cs(在构造函数中)我有这个:

OpenFileCommand = ReactiveCommand.CreateAsyncTask(async (o, ct) => await LoadFile(ct));
var whenButtonClick =
    Observable
        .Timer(TimeSpan.FromSeconds(10));
whenButtonClick.Subscribe(_ => Console.WriteLine());
OpenFileCommand
    .ExecuteAsync()
    .TakeUntil(whenButtonClick)
    .Subscribe(OnDocumentLoaded);

我的视图中有一个绑定到 LoadFileCommand 的"加载"按钮,但代码在创建视图模型后立即执行任务,而不是在用户单击按钮时执行任务。

顺便说一句,我想有另一个"取消"按钮,允许用户取消加载。

ReactiveCommand.CreateAsync task.如何使用按钮取消任务

订阅LoadFileCommand不会调用该命令。 在对命令调用其中一个执行方法之前,不会调用该命令。 在您的情况下,您想拨打LoadFileCommand.ExecuteAsync. 我相信,这将在你的情况下返回一个IObservable<File>。 释放对该可观察对象的订阅或以其他方式终止该可观察量将导致可观察量请求取消传递给委托中LoadFile的取消令牌。

我试图在这里创建一个 .NET 小提琴来演示,但它一直说程序集没有被引用,即使它显然是。 无论如何,如果您想使用它,可以将以下代码复制到 LinqPad 或控制台应用程序中:

var testCommand = ReactiveCommand.CreateAsyncTask(async (name, ct) =>
{
    // Do some long running work and periodically check if the
    // token has been cancelled.
    for (int i = 0; i < 5; i++)
    {
        Console.WriteLine(
            "{0} cancellation requested: {1}", 
            name, 
            ct.IsCancellationRequested);
        if (ct.IsCancellationRequested)
        {
            ct.ThrowIfCancellationRequested();
        }
        await Task.Delay(1000);
    }
});
var whenButtonClick =
    Observable
    .Timer(TimeSpan.FromSeconds(2));
// Execute a command that is cancelled when a button click happens.
// Note the TakeUntil(whenButtonClick)
testCommand
.ExecuteAsync("first")
.TakeUntil(whenButtonClick)
.Subscribe(
    onNext: _ => Console.WriteLine("first next"),
    onCompleted: () => Console.WriteLine("first completed"));
// Execute a command that runs to completion.
testCommand
.ExecuteAsync("second")
.Subscribe(
    onNext: _ => Console.WriteLine("second next"),
    onCompleted: () => Console.WriteLine("second completed"));

这是上述代码的输出。 您可以看到取消令牌确实请求取消:

首次请求取消:假
第二次取消请求:假
第二次取消请求:假
首次请求取消:假
首次完成
首次请求取消:真
第二次取消请求:假
第二次取消请求:假
第二次取消请求:假
第二页 下一页
第二次完成

编辑 - 可能的解决方案

所以我想我有一些东西可以在你的场景中工作,同时仍然允许你使用 Xaml 绑定。 我正在将取消逻辑推送到命令工厂方法中,而不是尝试获取单个调用并取消它们。

CancelOpenFileCommand = ReactiveCommand.Create();
LoadFileCommand = 
    ReactiveCommand
    .CreateAsyncObservable(_ =>
        Observable
        .FromAsync(cancellationToken => LoadFile(cancellationToken))
        .TakeUntil(CancelOpenFileCommand));

现在,如果您将要用于打开文件的按钮绑定到LoadFileCommand,并将要用于取消命令的按钮绑定到CancelOpenFileCommand则一切正常。

下面是一个使用我上面描述的相同模式的示例。 我用一个虚拟任务替换了LoadFile,该任务只包含一个循环五次的循环,在循环中,我将取消令牌的状态写入控制台,然后延迟一秒钟。 因此,该任务应该需要五秒钟才能完成。 但是我没有让它完成,而是在一秒钟后调用CancelOpenFileCommand。 这表明在调用CancelOpenFileCommand时取消令牌,并且命令提前终止。

var CancelOpenFileCommand = ReactiveCommand.Create();
CancelOpenFileCommand
.Subscribe(x => 
    Console
    .WriteLine(
        "{0} CancelOpenFileCommand Invoked", 
        DateTime.Now.TimeOfDay));
var LoadFile = new Func<CancellationToken, Task>(async cancellationToken =>
    {
        for (int i = 0; i < 5; i++)
        {
            Console
            .WriteLine(
                "{0} Cancellation requested: {1}", 
                DateTime.Now.TimeOfDay, 
                cancellationToken.IsCancellationRequested);             
            if (cancellationToken.IsCancellationRequested)
            {
                cancellationToken.ThrowIfCancellationRequested();
            }
            await Task.Delay(1000);
        }
    });
var LoadFileCommand = 
    ReactiveCommand
    .CreateAsyncObservable(
        name =>
            Observable
            .FromAsync(ct => LoadFile(ct))
            .TakeUntil(CancelOpenFileCommand));
LoadFileCommand.Execute(null);
Observable
.Timer(TimeSpan.FromSeconds(1))
.Subscribe(_ => CancelOpenFileCommand.Execute(null));

这是控制台输出:

19:04:57.6087252 请求取消:假
19:04:58.6157828 请求取消:假
19:04:58.6197830 取消打开文件命令
调用 19:04:59.6268406 请求取消:True