我一直在谷歌搜索,甚至Binging,我还没有想出任何令人满意的事情。
我有一个ViewModel,它有一些命令,例如:SaveCommand
,NewCommand
和DeleteCommand
。我的SaveCommand
执行保存到文件操作,我想要进行async
操作,以便用户界面不等待它。
我的SaveCommand
是AsyncCommand的一个实例,它实现了ICommand
。
SaveCommand = new AsyncCommand(
async param =>
{
Connection con = await Connection.GetInstanceAsync(m_configurationPath);
con.Shoppe.Configurations = new List<CouchDbConfig>(m_configurations);
await con.SaveConfigurationAsync(m_configurationPath);
//now that its saved, we reload the Data.
await LoadDataAsync(m_configurationPath);
},
...etc
现在我正在为我的ViewModel构建测试。在其中,我使用NewCommand
创建了一个新内容,我修改它然后使用SaveCommand
。
vm.SaveCommand.Execute(null);
Assert.IsFalse(vm.SaveCommand.CanExecute(null));
CanExecute
的{{1}}方法(未显示)应该在项目保存后立即返回SaveCommand
(保存未更改的项目没有意义)。但是,上面显示的Assert总是失败,因为我不是在等False
完成执行。
现在,我无法等待它完成执行,因为我无法做到。 SaveCommand
没有返回ICommand.Execute
。如果我更改Task
以使其AsyncCommand
返回Execute
,那么它就无法正确实现Task
界面。
因此,出于测试目的,我认为我现在唯一能做的就是ICommand
有一个新功能:
AsynCommand
因此,我的测试将运行{和public async Task ExecuteAsync(object param) { ... }
)await
函数,而XAML UI将运行ExecuteAsync
方法,而不是ICommand.Execute
。< / p>
我不会像我想的那样对我提出的求解方法感到高兴,并希望并希望有更好的方法。
我的建议,合理吗?还有更好的方法吗?
答案 0 :(得分:13)
你的建议是合理的,而且正是AsyncCommand
implementation created by Stephen Cleary所做的(他是最重要的experts on the subject of async代码恕我直言)
以下是文章中代码的完整实现(以及我为我使用的用例做的一些调整。)
<强> AsyncCommand.cs 强>
/*
* Based on the article: Patterns for Asynchronous MVVM Applications: Commands
* http://msdn.microsoft.com/en-us/magazine/dn630647.aspx
*
* Modified by Scott Chamberlain 11-19-2014
* - Added parameter support
* - Added the ability to shut off the single invocation restriction.
* - Made a non-generic version of the class that called the generic version with a <object> return type.
*/
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Infrastructure
{
public class AsyncCommand : AsyncCommand<object>
{
public AsyncCommand(Func<object, Task> command)
: base(async (parmater, token) => { await command(parmater); return null; }, null)
{
}
public AsyncCommand(Func<object, Task> command, Func<object, bool> canExecute)
: base(async (parmater, token) => { await command(parmater); return null; }, canExecute)
{
}
public AsyncCommand(Func<object, CancellationToken, Task> command)
: base(async (parmater, token) => { await command(parmater, token); return null; }, null)
{
}
public AsyncCommand(Func<object, CancellationToken, Task> command, Func<object, bool> canExecute)
: base(async (parmater, token) => { await command(parmater, token); return null; }, canExecute)
{
}
}
public class AsyncCommand<TResult> : AsyncCommandBase, INotifyPropertyChanged
{
private readonly Func<object, CancellationToken, Task<TResult>> _command;
private readonly CancelAsyncCommand _cancelCommand;
private readonly Func<object, bool> _canExecute;
private NotifyTaskCompletion<TResult> _execution;
private bool _allowMultipleInvocations;
public AsyncCommand(Func<object, Task<TResult>> command)
: this((parmater, token) => command(parmater), null)
{
}
public AsyncCommand(Func<object, Task<TResult>> command, Func<object, bool> canExecute)
: this((parmater, token) => command(parmater), canExecute)
{
}
public AsyncCommand(Func<object, CancellationToken, Task<TResult>> command)
: this(command, null)
{
}
public AsyncCommand(Func<object, CancellationToken, Task<TResult>> command, Func<object, bool> canExecute)
{
_command = command;
_canExecute = canExecute;
_cancelCommand = new CancelAsyncCommand();
}
public override bool CanExecute(object parameter)
{
var canExecute = _canExecute == null || _canExecute(parameter);
var executionComplete = (Execution == null || Execution.IsCompleted);
return canExecute && (AllowMultipleInvocations || executionComplete);
}
public override async Task ExecuteAsync(object parameter)
{
_cancelCommand.NotifyCommandStarting();
Execution = new NotifyTaskCompletion<TResult>(_command(parameter, _cancelCommand.Token));
RaiseCanExecuteChanged();
await Execution.TaskCompletion;
_cancelCommand.NotifyCommandFinished();
RaiseCanExecuteChanged();
}
public bool AllowMultipleInvocations
{
get { return _allowMultipleInvocations; }
set
{
if (_allowMultipleInvocations == value)
return;
_allowMultipleInvocations = value;
OnPropertyChanged();
}
}
public ICommand CancelCommand
{
get { return _cancelCommand; }
}
public NotifyTaskCompletion<TResult> Execution
{
get { return _execution; }
private set
{
_execution = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
private sealed class CancelAsyncCommand : ICommand
{
private CancellationTokenSource _cts = new CancellationTokenSource();
private bool _commandExecuting;
public CancellationToken Token { get { return _cts.Token; } }
public void NotifyCommandStarting()
{
_commandExecuting = true;
if (!_cts.IsCancellationRequested)
return;
_cts = new CancellationTokenSource();
RaiseCanExecuteChanged();
}
public void NotifyCommandFinished()
{
_commandExecuting = false;
RaiseCanExecuteChanged();
}
bool ICommand.CanExecute(object parameter)
{
return _commandExecuting && !_cts.IsCancellationRequested;
}
void ICommand.Execute(object parameter)
{
_cts.Cancel();
RaiseCanExecuteChanged();
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
private void RaiseCanExecuteChanged()
{
CommandManager.InvalidateRequerySuggested();
}
}
}
}
<强> AsyncCommandBase.cs 强>
/*
* Based on the article: Patterns for Asynchronous MVVM Applications: Commands
* http://msdn.microsoft.com/en-us/magazine/dn630647.aspx
*/
using System;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Infrastructure
{
public abstract class AsyncCommandBase : IAsyncCommand
{
public abstract bool CanExecute(object parameter);
public abstract Task ExecuteAsync(object parameter);
public async void Execute(object parameter)
{
await ExecuteAsync(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
protected void RaiseCanExecuteChanged()
{
CommandManager.InvalidateRequerySuggested();
}
}
}
<强> NotifyTaskCompletion.cs 强>
/*
* Based on the article: Patterns for Asynchronous MVVM Applications: Commands
* http://msdn.microsoft.com/en-us/magazine/dn630647.aspx
*
* Modifed by Scott Chamberlain on 12/03/2014
* Split in to two classes, one that does not return a result and a
* derived class that does.
*/
using System;
using System.ComponentModel;
using System.Threading.Tasks;
namespace Infrastructure
{
public sealed class NotifyTaskCompletion<TResult> : NotifyTaskCompletion
{
public NotifyTaskCompletion(Task<TResult> task)
: base(task)
{
}
public TResult Result
{
get
{
return (Task.Status == TaskStatus.RanToCompletion) ?
((Task<TResult>)Task).Result : default(TResult);
}
}
}
public class NotifyTaskCompletion : INotifyPropertyChanged
{
public NotifyTaskCompletion(Task task)
{
Task = task;
if (!task.IsCompleted)
TaskCompletion = WatchTaskAsync(task);
else
TaskCompletion = Task;
}
private async Task WatchTaskAsync(Task task)
{
try
{
await task;
}
catch
{
//This catch is intentionally empty, the errors will be handled lower on the "task.IsFaulted" branch.
}
var propertyChanged = PropertyChanged;
if (propertyChanged == null)
return;
propertyChanged(this, new PropertyChangedEventArgs("Status"));
propertyChanged(this, new PropertyChangedEventArgs("IsCompleted"));
propertyChanged(this, new PropertyChangedEventArgs("IsNotCompleted"));
if (task.IsCanceled)
{
propertyChanged(this, new PropertyChangedEventArgs("IsCanceled"));
}
else if (task.IsFaulted)
{
propertyChanged(this, new PropertyChangedEventArgs("IsFaulted"));
propertyChanged(this, new PropertyChangedEventArgs("Exception"));
propertyChanged(this, new PropertyChangedEventArgs("InnerException"));
propertyChanged(this, new PropertyChangedEventArgs("ErrorMessage"));
}
else
{
propertyChanged(this, new PropertyChangedEventArgs("IsSuccessfullyCompleted"));
propertyChanged(this, new PropertyChangedEventArgs("Result"));
}
}
public Task Task { get; private set; }
public Task TaskCompletion { get; private set; }
public TaskStatus Status { get { return Task.Status; } }
public bool IsCompleted { get { return Task.IsCompleted; } }
public bool IsNotCompleted { get { return !Task.IsCompleted; } }
public bool IsSuccessfullyCompleted
{
get
{
return Task.Status ==
TaskStatus.RanToCompletion;
}
}
public bool IsCanceled { get { return Task.IsCanceled; } }
public bool IsFaulted { get { return Task.IsFaulted; } }
public AggregateException Exception { get { return Task.Exception; } }
public Exception InnerException
{
get
{
return (Exception == null) ?
null : Exception.InnerException;
}
}
public string ErrorMessage
{
get
{
return (InnerException == null) ?
null : InnerException.Message;
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
答案 1 :(得分:3)
看起来答案是使用带有AsyncCommand
对象的标志。使用Executing
方法中AsyncCommand
的{{1}}标志将确保用户在另一个实例运行时无法执行该命令。
同样使用单元测试,您可以使用while循环使其在断言后等待:
CanExecute
这样测试就会彻底退出。
答案 2 :(得分:1)
做while (vm.SaveCommand.Executing) ;
似乎是忙碌中,而我更愿意避免这种情况。
使用斯蒂芬·克莱里(Stephen Cleary)的AsyncCommand
的另一种解决方案似乎对这种简单的任务有些过分了。。
我提出的方法不会破坏封装-Save
方法不会暴露任何内部信息。它只是提供了另一种访问相同功能的方法。
我的解决方案似乎以简单明了的方式涵盖了所有需要的内容。
我建议重构该代码:
SaveCommand = new AsyncCommand(
async param =>
{
Connection con = await Connection.GetInstanceAsync(m_configurationPath);
con.Shoppe.Configurations = new List<CouchDbConfig>(m_configurations);
await con.SaveConfigurationAsync(m_configurationPath);
//now that its saved, we reload the Data.
await LoadDataAsync(m_configurationPath);
});
收件人:
SaveCommand = new RelayCommand(async param => await Save(param));
public async Task Save(object param)
{
Connection con = await Connection.GetInstanceAsync(m_configurationPath);
con.Shoppe.Configurations = new List<CouchDbConfig>(m_configurations);
await con.SaveConfigurationAsync(m_configurationPath);
//now that its saved, we reload the Data.
await LoadDataAsync(m_configurationPath);
}
仅需注意:我将AsyncCommand
更改为RelayCommand
,可以在任何MVVM框架中找到它。它只是接收一个动作作为参数,并在调用ICommand.Execute
方法时运行该动作。
我使用了支持async
测试的NUnit框架作为示例:
[Test]
public async Task MyViewModelWithAsyncCommandsTest()
{
// Arrange
// do view model initialization here
// Act
await vm.Save(param);
// Assert
// verify that what what you expected actually happened
}
,然后在视图中像平常一样绑定命令:
Command="{Binding SaveCommand}"