c# - 我将如何去创建一个异步命令
问题描述
我有一个在 C# 中使用 MVVM 的应用程序,所以它是一个 wpf 应用程序,我有一个普通的 Relaycommand,但是这个命令只能采取行动,所以基本上只有普通的方法,如果我点击一个按钮然后激活异步方法怎么办我将如何制作一个可以同时采用异步和同步代码的 Relaycommand?这是我到目前为止所尝试的,我还查看了此链接https://docs.microsoft.com/en-us/archive/msdn-magazine/2014/march/async-programming-patterns-for-asynchronous-mvvm -applications-data-binding和此链接https://johnthiriet.com/mvvm-going-async-with-async-command/
using Microsoft.JScript;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace DataConverter.Command
{
public class RelayCommandAsync : ICommand
{
private readonly Func executedMethod;
private readonly Func canExecuteMethod;
public event EventHandler CanExecuteChanged;
public RelayCommandAsync(Func execute) : this(execute, null) { }
public RelayCommandAsync(Func execute, Func canExecute)
{
this.executedMethod = execute ?? throw new ArgumentNullException("execute");
this.canExecuteMethod = canExecute;
}
public bool CanExecute(object parameter) => this.canExecuteMethod == null || this.canExecuteMethod((T)parameter);
public async void Execute(object parameter) => await this.executedMethod((T)parameter);
public void OnCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
解决方案
推荐阅读
- java - 处理对话框 onclicklistener 时片段中的 NullPoinerException
- c++ - 允许使用 GCC 的特定未定义引用
- ios - 在移动 Chrome 中重定向后有时不会发送 Cookie
- javascript - 无法在 html 模式中编辑表单
- winapi - STN_CLICKED 按下了哪个静态控件?
- bash - 如果您只知道文件名的结尾,则 cygwin bash 完成
- python - rdkit:如何绘制高分辨率化学结构
- .net - Azure 云服务(经典)- 单个实例缺少根 CA / SSL 证书无法验证
- azure - Azure Key Vault - CertificateClient - import_certificate:(BadParameter)属性策略具有无效值
- ruby - 如何阻止 shift 影响数组的其他实例