在C#中使用Command進行異步操作的步驟如下:
下面是一個示例代碼:
using System;
using System.Threading.Tasks;
using System.Windows.Input;
public class AsyncCommand : ICommand
{
private Func<Task> _execute;
private Func<bool> _canExecute;
public AsyncCommand(Func<Task> execute, Func<bool> canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute();
}
public async void Execute(object parameter)
{
await _execute();
}
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
使用示例:
public class ViewModel
{
public AsyncCommand MyCommand { get; set; }
public ViewModel()
{
MyCommand = new AsyncCommand(ExecuteAsync, () => true);
}
public async Task ExecuteAsync()
{
await Task.Delay(1000);
Console.WriteLine("Async operation completed");
}
}
class Program
{
static async Task Main(string[] args)
{
var viewModel = new ViewModel();
await viewModel.MyCommand.Execute(null);
}
}
在上面的示例中,我們創建了一個AsyncCommand類來實現異步操作的Command,然后在ViewModel中使用這個Command來執行異步操作。