2013-02-19 49 views
5

我正在寻找在图层之间进行异步通信的最佳实践。 我使用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

​​

+0

不会让任务模式更容易阅读吗?当然,与异步/等待.. – JustAnotherUserYouMayKnow 2013-02-19 09:25:10

+0

,但据我所知只是因为.net 4.5可用?!? – 2013-02-19 09:52:32

+0

有一个NuGet包可以支持4.0和silverlight 5.将它安装到您的项目中,它就像一个魅力! http://nuget.org/packages/Microsoft.CompilerServices.AsyncTargetingPack/ – JustAnotherUserYouMayKnow 2013-02-19 12:21:12

回答

1

嗯,我想说模型的fecthing,并把它变成视图模型是异步。谁来做,取决于体系结构,它可以在视图模型本身上完成,也可以使用控制器层进行异步加载和映射初始化虚拟机以查看。另外背景工作者是过去应该使用Task类进行并行操作。当然,不要忘记在通知虚拟机发生更改时通过调度程序调用。

代码示例:

Task<string>.Factory.StartNew(() => 
{ 
    string text = GetArticleText(); 
    Application.Current.Dispatcher.BeginInvoke(new Action(()=>MyTextProperty = text)); 
}); 
1

我建议把异步代码在您的视图模型,并留下你的模型来存储数据。当我开始使用MVVM时,我学到的第一件事就是从我的模型中移除逻辑,并将其保留在ViewModels中。尽管我会说,只要所有阅读代码的人都能理解它,只要你把代码放在哪里就行了。