Skip to content

Instantly share code, notes, and snippets.

@sandorfr
Created October 31, 2012 22:40
Show Gist options
  • Save sandorfr/3990410 to your computer and use it in GitHub Desktop.
Save sandorfr/3990410 to your computer and use it in GitHub Desktop.
using System;
using System.Threading.Tasks;
using System.Windows.Input;
namespace ImprovedDelegateCommand
{
public class AsyncDelegateCommand<T> : ICommand
{
private Func<T, bool> canExecute;
private Func<T, Task> execute;
private bool isRunning;
public AsyncDelegateCommand(Func<T, Task> execute, Func<T, bool> canExecute = null)
{
this.execute = execute;
this.canExecute = canExecute ?? new Func<T, bool>(x => true);
}
public void RaiseCanExecuteChange()
{
if (CanExecuteChanged != null)
CanExecuteChanged(this, EventArgs.Empty);
}
public bool CanExecute(object parameter)
{
return !isRunning && canExecute((T)parameter);
}
public event EventHandler CanExecuteChanged;
public async void Execute(object parameter)
{
isRunning = true;
try
{
this.RaiseCanExecuteChange();
await execute((T)parameter);
}
finally
{
isRunning = false;
this.RaiseCanExecuteChange();
}
}
}
public class AsyncDelegateCommand : ICommand
{
private Func<bool> canExecute;
private Func<Task> execute;
private bool isRunning;
public AsyncDelegateCommand(Func<Task> execute, Func<bool> canExecute = null)
{
this.execute = execute;
this.canExecute = canExecute ?? new Func<bool>(() => true);
}
public void RaiseCanExecuteChange()
{
if (CanExecuteChanged != null)
CanExecuteChanged(this, EventArgs.Empty);
}
public bool CanExecute(object parameter)
{
return !isRunning && canExecute();
}
public event EventHandler CanExecuteChanged;
public async void Execute(object parameter)
{
isRunning = true;
try
{
this.RaiseCanExecuteChange();
await execute();
}
finally
{
isRunning = false;
this.RaiseCanExecuteChange();
}
}
}
}
public bool CanExecute(object parameter)
{
return !isRunning && canExecute();
}
private Func<bool> canExecute;
private Func<Task> execute;
private bool isRunning;
public AsyncDelegateCommand(Func<Task> execute, Func<bool> canExecute = null)
{
this.execute = execute;
this.canExecute = canExecute ?? new Func<bool>(() => true);
}
public async void Execute(object parameter)
{
isRunning = true;
try
{
this.RaiseCanExecuteChange();
await execute();
}
finally
{
isRunning = false;
this.RaiseCanExecuteChange();
}
}
public class DelegateCommand : ICommand
{
private Func<bool> canExecute;
private Action execute;
public DelegateCommand(Action execute, Func<bool> canExecute = null)
{
this.execute = execute;
this.canExecute = canExecute ?? new Func<bool>(() => true);
}
public void RaiseCanExecuteChange()
{
if (CanExecuteChanged != null)
CanExecuteChanged(this, EventArgs.Empty);
}
public bool CanExecute(object parameter)
{
return (canExecute());
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
execute();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment