我正在寻找在图层之间进行异步通信的最佳实践。 我使用mvvm light toolkit什么是MVVM中的异步? Model或ViewModel。最佳实践?
目前我使用一个BackgroundWorker在模型,因为我看到这个在自动生成的代码。不是背景工作者,而是异步电话。
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();
}
现在我发现它实现在视图模型的异步部分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://csharperimage.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
不会让任务模式更容易阅读吗?当然,与异步/等待.. – JustAnotherUserYouMayKnow 2013-02-19 09:25:10
,但据我所知只是因为.net 4.5可用?!? – 2013-02-19 09:52:32
有一个NuGet包可以支持4.0和silverlight 5.将它安装到您的项目中,它就像一个魅力! http://nuget.org/packages/Microsoft.CompilerServices.AsyncTargetingPack/ – JustAnotherUserYouMayKnow 2013-02-19 12:21:12