Created
November 14, 2019 23:57
-
-
Save TheFo2sh/f2155b1855438d3b02834140f66a9bf8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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