Skip to content

Instantly share code, notes, and snippets.

@TheFo2sh
Last active September 9, 2019 02:24
Show Gist options
  • Save TheFo2sh/3db821cefdd3ead6ff5630612681a26d to your computer and use it in GitHub Desktop.
Save TheFo2sh/3db821cefdd3ead6ff5630612681a26d to your computer and use it in GitHub Desktop.
public class CommandAsync<T> : IMPCommand
{
private readonly Func<T,Task> _executeTask;
private readonly Predicate<object> _canExecute;
private bool _locked;
public CommandAsync(Func<T, Task> executeTask) : this(executeTask, o => true)
{
}
public CommandAsync(Func<T, Task> executeTask, Predicate<object> canExecute)
{
_executeTask = executeTask;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return !_locked && _canExecute.Invoke(parameter);
}
public async void Execute(object parameter)
{
try
{
_locked = true;
CanExecuteChanged?.Invoke(this, new CommandExecuteChangedArgs("Command Looked for async execution"));
await _executeTask.Invoke((T) parameter);
}
finally
{
_locked = false;
CanExecuteChanged?.Invoke(this, new CommandExecuteChangedArgs("Command Unlooked for async execution terminated"));
}
}
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