// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace CommunityToolkit.Mvvm.Input;
///
/// A generic command that provides a more specific version of .
///
/// The type of parameter being passed as input to the callbacks.
public sealed class AsyncRelayCommand : IAsyncRelayCommand
{
///
/// The to invoke when is used.
///
private readonly Func? execute;
///
/// The cancelable to invoke when is used.
///
private readonly Func? cancelableExecute;
///
/// The optional action to invoke when is used.
///
private readonly Predicate? canExecute;
///
/// Indicates whether or not concurrent executions of the command are allowed.
///
private readonly bool allowConcurrentExecutions;
///
/// The instance to use to cancel .
///
private CancellationTokenSource? cancellationTokenSource;
///
public event PropertyChangedEventHandler? PropertyChanged;
///
public event EventHandler? CanExecuteChanged;
///
/// Initializes a new instance of the class that can always execute.
///
/// The execution logic.
/// See notes in .
/// Thrown if is .
public AsyncRelayCommand(Func execute)
{
ArgumentNullException.ThrowIfNull(execute);
this.execute = execute;
this.allowConcurrentExecutions = true;
}
///
/// Initializes a new instance of the class that can always execute.
///
/// The execution logic.
/// Whether or not to allow concurrent executions of the command.
/// See notes in .
/// Thrown if is .
public AsyncRelayCommand(Func execute, bool allowConcurrentExecutions)
{
ArgumentNullException.ThrowIfNull(execute);
this.execute = execute;
this.allowConcurrentExecutions = allowConcurrentExecutions;
}
///
/// Initializes a new instance of the class that can always execute.
///
/// The cancelable execution logic.
/// See notes in .
/// Thrown if is .
public AsyncRelayCommand(Func cancelableExecute)
{
ArgumentNullException.ThrowIfNull(cancelableExecute);
this.cancelableExecute = cancelableExecute;
this.allowConcurrentExecutions = true;
}
///
/// Initializes a new instance of the class that can always execute.
///
/// The cancelable execution logic.
/// Whether or not to allow concurrent executions of the command.
/// See notes in .
/// Thrown if is .
public AsyncRelayCommand(Func cancelableExecute, bool allowConcurrentExecutions)
{
ArgumentNullException.ThrowIfNull(cancelableExecute);
this.cancelableExecute = cancelableExecute;
this.allowConcurrentExecutions = allowConcurrentExecutions;
}
///
/// Initializes a new instance of the class.
///
/// The execution logic.
/// The execution status logic.
/// See notes in .
/// Thrown if or are .
public AsyncRelayCommand(Func execute, Predicate canExecute)
{
ArgumentNullException.ThrowIfNull(execute);
ArgumentNullException.ThrowIfNull(canExecute);
this.execute = execute;
this.canExecute = canExecute;
this.allowConcurrentExecutions = true;
}
///
/// Initializes a new instance of the class.
///
/// The execution logic.
/// The execution status logic.
/// Whether or not to allow concurrent executions of the command.
/// See notes in .
/// Thrown if or are .
public AsyncRelayCommand(Func execute, Predicate canExecute, bool allowConcurrentExecutions)
{
ArgumentNullException.ThrowIfNull(execute);
ArgumentNullException.ThrowIfNull(canExecute);
this.execute = execute;
this.canExecute = canExecute;
this.allowConcurrentExecutions = allowConcurrentExecutions;
}
///
/// Initializes a new instance of the class.
///
/// The cancelable execution logic.
/// The execution status logic.
/// See notes in .
/// Thrown if or are .
public AsyncRelayCommand(Func cancelableExecute, Predicate canExecute)
{
ArgumentNullException.ThrowIfNull(cancelableExecute);
ArgumentNullException.ThrowIfNull(canExecute);
this.cancelableExecute = cancelableExecute;
this.canExecute = canExecute;
this.allowConcurrentExecutions = true;
}
///
/// Initializes a new instance of the class.
///
/// The cancelable execution logic.
/// The execution status logic.
/// Whether or not to allow concurrent executions of the command.
/// See notes in .
/// Thrown if or are .
public AsyncRelayCommand(Func cancelableExecute, Predicate canExecute, bool allowConcurrentExecutions)
{
ArgumentNullException.ThrowIfNull(cancelableExecute);
ArgumentNullException.ThrowIfNull(canExecute);
this.cancelableExecute = cancelableExecute;
this.canExecute = canExecute;
this.allowConcurrentExecutions = allowConcurrentExecutions;
}
private Task? executionTask;
///
public Task? ExecutionTask
{
get => this.executionTask;
private set
{
if (ReferenceEquals(this.executionTask, value))
{
return;
}
this.executionTask = value;
PropertyChanged?.Invoke(this, AsyncRelayCommand.ExecutionTaskChangedEventArgs);
PropertyChanged?.Invoke(this, AsyncRelayCommand.IsRunningChangedEventArgs);
PropertyChanged?.Invoke(this, AsyncRelayCommand.CanBeCanceledChangedEventArgs);
if (value?.IsCompleted ?? true)
{
return;
}
static async void MonitorTask(AsyncRelayCommand @this, Task task)
{
try
{
await task;
}
catch
{
}
if (ReferenceEquals(@this.executionTask, task))
{
@this.PropertyChanged?.Invoke(@this, AsyncRelayCommand.ExecutionTaskChangedEventArgs);
@this.PropertyChanged?.Invoke(@this, AsyncRelayCommand.IsRunningChangedEventArgs);
@this.PropertyChanged?.Invoke(@this, AsyncRelayCommand.CanBeCanceledChangedEventArgs);
}
}
MonitorTask(this, value!);
}
}
///
public bool CanBeCanceled => this.cancelableExecute is not null && IsRunning;
///
public bool IsCancellationRequested => this.cancellationTokenSource?.IsCancellationRequested == true;
///
public bool IsRunning => ExecutionTask?.IsCompleted == false;
///
public void NotifyCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool CanExecute(T? parameter)
{
bool canExecute = this.canExecute?.Invoke(parameter) != false;
return canExecute && (this.allowConcurrentExecutions || ExecutionTask?.IsCompleted != false);
}
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool CanExecute(object? parameter)
{
if (default(T) is not null &&
parameter is null)
{
return false;
}
return CanExecute((T?)parameter);
}
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Execute(T? parameter)
{
_ = ExecuteAsync(parameter);
}
///
public void Execute(object? parameter)
{
_ = ExecuteAsync((T?)parameter);
}
///
public Task ExecuteAsync(T? parameter)
{
if (CanExecute(parameter))
{
// Non cancelable command delegate
if (this.execute is not null)
{
return ExecutionTask = this.execute(parameter);
}
// Cancel the previous operation, if one is pending
this.cancellationTokenSource?.Cancel();
CancellationTokenSource cancellationTokenSource = this.cancellationTokenSource = new();
PropertyChanged?.Invoke(this, AsyncRelayCommand.IsCancellationRequestedChangedEventArgs);
// Invoke the cancelable command delegate with a new linked token
return ExecutionTask = this.cancelableExecute!(parameter, cancellationTokenSource.Token);
}
return Task.CompletedTask;
}
///
public Task ExecuteAsync(object? parameter)
{
return ExecuteAsync((T?)parameter);
}
///
public void Cancel()
{
this.cancellationTokenSource?.Cancel();
PropertyChanged?.Invoke(this, AsyncRelayCommand.IsCancellationRequestedChangedEventArgs);
PropertyChanged?.Invoke(this, AsyncRelayCommand.CanBeCanceledChangedEventArgs);
}
}