使用Command来执行异步操作,并在Command中实现ICancellableCommand接口来处理取消操作,避免界面冻结。
代码示例:
public class AsyncCommand : ICommand, ICancellableCommand
{
private readonly Func _execute;
private bool _isExecuting;
public AsyncCommand(Func execute)
{
_execute = execute;
}
public bool CanExecute(object parameter)
{
return !_isExecuting;
}
public async void Execute(object parameter)
{
_isExecuting = true;
try
{
await _execute();
}
finally
{
_isExecuting = false;
}
}
public void Cancel()
{
// TODO: Implement cancellation
}
public event EventHandler CanExecuteChanged;
}
使用方法:
private AsyncCommand _asyncCommand;
public ViewModel()
{
_asyncCommand = new AsyncCommand(ExecuteAsync);
}
public ICommand AsyncCommand => _asyncCommand;
private async Task ExecuteAsync()
{
// TODO: Implement asynchronous operation
}