【发布时间】:2020-08-05 07:35:49
【问题描述】:
我在 ac# wpf mvvm 应用程序中有一个不工作的 asyncRelayCommand 我有点明白我需要一个方法来解决这个问题,但我经历的指南没有提到如何制作一个 https://johnthiriet.com/mvvm-going-async-with-async-command/ 这是我经历的指南这是我的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using GalaSoft.MvvmLight;
namespace DataConverter.Command
{
public interface IAsyncCommand<T> : ICommand
{
Task ExecuteAsync(T parameter);
bool CanExecute(T parameter);
}
public class AsyncCommand<T> : IAsyncCommand<T>
{
public event EventHandler CanExecuteChanged;
private bool _isExecuting;
private readonly Func<T, Task> _execute;
private readonly Func<T, bool> _canExecute;
private readonly IErrorHandler _errorHandler;
public AsyncCommand(Func<T, Task> execute, Func<T, bool> canExecute = null, IErrorHandler errorHandler = null)
{
_execute = execute;
_canExecute = canExecute;
_errorHandler = errorHandler;
}
public bool CanExecute(T parameter)
{
return !_isExecuting && (_canExecute?.Invoke(parameter) ?? true);
}
public async Task ExecuteAsync(T parameter)
{
if (CanExecute(parameter))
{
try
{
_isExecuting = true;
await _execute(parameter);
}
finally
{
_isExecuting = false;
}
}
RaiseCanExecuteChanged();
}
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
#region Explicit implementations
bool ICommand.CanExecute(object parameter)
{
return CanExecute((T)parameter);
}
void ICommand.Execute(object parameter)
{
ExecuteAsync((T)parameter).FireAndForgetSafeAsync(_errorHandler);
}
#endregion
}
}
谁能告诉我如何制作一个这样它会起作用我真的不明白为什么指南没有提到它但是是的
【问题讨论】:
-
你的意思是:“我需要一个方法”???。他提到它:Submit = new AsyncCommand(ExecuteSubmitAsync, CanExecuteSubmit);
-
但是我的 fire 和 async 给了我一个错误
-
或者你是说使用它可以摆脱错误
-
你的意思是 SafeFireAndForget 方法吗?
-
FireAndForgetSafeAsync
标签: c# asynchronous mvvm icommand