我正在寻找层间异步通信的最佳实践。 我正在使用 mvvm light toolkit
目前我在 model 中使用了一个 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它实现了 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));
}
}
我对最佳实践有点困惑?我读了很多文章。但不知何故,他们总是有不同的意见。有没有规定在正常维护的情况下最好的兼容?
一些思考
型号:
http://csharperimage.jeremylikness.com/2009/12/simplifying-asynchronous-calls-in.html
http://www.dzone.com/articles/mvvmlight-and-async
View 模型
http://www.codeproject.com/Articles/123183/Asynchronus-MVVM-Stop-the-Dreaded-Dead-GUI-Problem
http://www.codeproject.com/Articles/441752/Async-MVVM-Modern-UI
最佳答案
好吧,我会说模型的生成和将其转换为 View 模型是异步的。谁来做,取决于架构,它可以在 View 模型本身上完成,也可以使用 Controller 层进行异步加载和初始化 VM 的映射以查看。此外,后台工作人员过去应该使用 Task 类进行并行操作。当然,当从 VM 通知 View 更改时,不要忘记通过调度程序调用。
代码示例:
Task<string>.Factory.StartNew(() =>
{
string text = GetArticleText();
Application.Current.Dispatcher.BeginInvoke(new Action(()=>MyTextProperty = text));
});
关于c# - MVVM 中的异步是什么?模型或 View 模型。最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14953716/