Skip to content

Instantly share code, notes, and snippets.

@TheFo2sh
Created November 14, 2019 23:57
Show Gist options
  • Save TheFo2sh/f2155b1855438d3b02834140f66a9bf8 to your computer and use it in GitHub Desktop.
Save TheFo2sh/f2155b1855438d3b02834140f66a9bf8 to your computer and use it in GitHub Desktop.
public class CommandAsync<T> : ICommand
{
private CancellationTokenSource cancellationTokenSource;
private readonly Func<T, CancellationToken, Task> _executeTask;
private readonly Predicate<T> _canExecute;
private bool _locked;
public CommandAsync(Func<T,CancellationToken, Task> executeTask) : this(executeTask, o => true)
{
}
public CommandAsync(Func<T, CancellationToken, Task> executeTask, Predicate<T> canExecute)
{
cancellationTokenSource = new CancellationTokenSource();
_executeTask = executeTask;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute.Invoke((T)parameter);
}
public async void Execute(object parameter)
{
try
{
if (_locked)
{
cancellationTokenSource.Cancel();
cancellationTokenSource = new CancellationTokenSource();
}
_locked = true;
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
await _executeTask.Invoke((T)parameter, cancellationTokenSource.Token);
}
finally
{
_locked = false;
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
public event EventHandler CanExecuteChanged;
public void ChangeCanExecute()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment