首页 > 解决方案 > 我将如何去创建一个异步命令

问题描述

我有一个在 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);
    }
}

标签: c#asynchronousmvvm

解决方案


推荐阅读