Catalog/CatalogLite/AsyncCommand.cs

52 lines
1.3 KiB
C#
Raw Normal View History

using Avalonia.Threading;
2026-05-26 21:47:55 +02:00
using System.Windows.Input;
namespace CatalogLite;
public sealed class AsyncCommand : ICommand
{
private readonly Func<Task> _execute;
private readonly Func<bool>? _canExecute;
private bool _isExecuting;
public AsyncCommand(Func<Task> execute, Func<bool>? canExecute = null)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
_canExecute = canExecute;
}
public event EventHandler? CanExecuteChanged;
public bool CanExecute(object? parameter) => !_isExecuting && (_canExecute?.Invoke() ?? true);
public async void Execute(object? parameter)
{
if (!CanExecute(parameter))
{
return;
}
try
{
_isExecuting = true;
RaiseCanExecuteChanged();
await _execute().ConfigureAwait(false);
}
finally
{
_isExecuting = false;
RaiseCanExecuteChanged();
}
}
public void RaiseCanExecuteChanged()
{
if (Dispatcher.UIThread.CheckAccess())
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
return;
}
Dispatcher.UIThread.Post(() => CanExecuteChanged?.Invoke(this, EventArgs.Empty));
}
2026-05-26 21:47:55 +02:00
}