mas*_*_99 5 .net c# wpf mvvm mvvm-light
我正在寻找在层之间进行异步通信的最佳实践.我正在使用mvvm light工具包
目前我在模型中使用了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();
}
Run Code Online (Sandbox Code Playgroud)
现在我找到了AsyncDelegateCommand,它实现了ViewModel中的异步部分.
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));
}
}
Run Code Online (Sandbox Code Playgroud)
我对最佳做法有点困惑?我读了很多文章.但不知何故,他们总是不同的意见.是否有任何规定在正常维护下保持最佳兼容性?
一些思考的食物
模型:
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
http://www.codeproject.com/Articles/441752/Async-MVVM-Modern-UI
好吧,我想说模型的转换并将其转换为视图模型是异步的。谁来做这件事取决于架构,它可以在视图模型本身上完成,也可以使用控制器层进行此类异步加载和初始化虚拟机到视图的映射。此外,后台工作人员过去您应该使用任务类进行并行操作。当然,在通知虚拟机更改视图时,不要忘记通过调度程序进行调用。
代码示例:
Task<string>.Factory.StartNew(() =>
{
string text = GetArticleText();
Application.Current.Dispatcher.BeginInvoke(new Action(()=>MyTextProperty = text));
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
644 次 |
| 最近记录: |