我正在寻找在层之间进行异步通信的最佳实践。我正在使用mvvm light 工具包
目前我在模型中使用了一个后台工作者,因为我在自动生成的代码中看到了这一点。不是后台工作人员,而是异步调用。
public void GetConfig(Action<Config, Exception> callback)
{
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += (backgroundWorkerSender, backgroundWorkerArgs) =>
{
try
{
backgroundWorkerArgs.Result = AppEnvironment.Instance.Config;
}
catch (Exception exception)
{
backgroundWorkerArgs.Result = null;
}
};
backgroundWorker.RunWorkerCompleted += (backgroundWorkerSender, backgroundWorkerArgs) =>
{
if (backgroundWorkerArgs.Result != null)
{
callback((Config) backgroundWorkerArgs.Result, null);
}
else
{
/* ToDo: exceptionhandling */
}
};
backgroundWorker.RunWorkerAsync();
}
现在我找到了在 ViewModel 中实现异步部分的AsyncDelegateCommand 。
private ICommand _refreshObjectDefinitionCommand;
public ICommand RefreshObjectDefinitionCommand
{
get
{
return _refreshObjectDefinitionCommand
?? (_refreshObjectDefinitionCommand = new AsyncDelegateCommand(delegate
{
IsBusy = true;
_dataService.GetObjectDefinition(
(xmlObjectDef, errorConfig) =>
{
if (errorConfig != null)
{
/* ToDo Lenz: exceptionhandling */
return;
}
ObjectDefinition = xmlObjectDef;
});
_dataService.GetObjectDefinitionTreeView(
(treenodes, errorConfig) =>
{
if (errorConfig != null)
{
/* ToDo Lenz: exceptionhandling */
return;
}
TreeNodes = treenodes;
});
},
() => _isConnected, o => IsBusy = false, exception => IsBusy = false));
}
}
我对最佳做法有点困惑?我读过很多文章。但不知何故,他们总是有不同的意见。是否有任何规定可以在正常努力下保持最佳兼容性?
一些思考的食物
模型:
http://cshaperimage.jeremylikness.com/2009/12/simplifying-asynchronous-calls-in.html
http://www.dzone.com/articles/mvvmlight-and-async
视图模型
http://www.codeproject.com/Articles/123183/Asynchronus-MVVM-Stop-the-Dreaded-Dead-GUI-Problem
http://www.codeproject.com/Articles/441752/Async-MVVM-Modern-UI