2011-06-27 52 views
1

我有一个从数据库中检索信息的wcf。从wcf服务获取异步数据

我也有一个Silverlight客户端应用程序引用该服务并使用它来检索数据。

public void init(ref Cluster cluster) 
{ 
    _SelectedCluster = cluster; 
    MyEntities svc = new MyEntities(new Uri("http://localhost:49672/MyDataService.svc/")); 
     docs = new DataServiceCollection<EC_Documents>(); 
     var query = from c in svc.EC_Documents 
        where c.clusterID == _SelectedNode.ID 
        orderby c.clusterID 
        select c; 

     docs.LoadCompleted += docs_LoadCompleted;  

    docs.LoadAsync(query); 
} 
    private void docs_LoadCompleted(object sender, LoadCompletedEventArgs e) 
    { 
     if (e.Error == null) 
     { 

      if (docs.Continuation != null) 
      { 
       docs.LoadNextPartialSetAsync(); 
      } 
      else 
      { 
       _SelectedCluster.Value = docs.Count; 

      } 
     } 
    } 

因为调用是异步的,我不得不做出文档类的成员,并在docs_LoadCompleted方法检查其计数。

我还有一个_SelectedCluster,它是Cluster类型的对象,作为类中的成员,它在迭代中保存当前的集群对象。

我有一个问题,分配结果到当前选定的节点_SelectedCluster.Value成员。

因为调用是异步的,所以我不能遍历所有的集群对象并同步分配结果。如果这样做,分配将始终在迭代中的最后一个集群上。

有什么建议吗?

回答

2

重新安排你的代码从封闭受益: -

public void init(Cluster cluster) 
{ 
    MyEntities svc = new MyEntities(new Uri("http://localhost:49672/MyDataService.svc/")); 
     var docs = new DataServiceCollection<EC_Documents>(); 
     var query = from c in svc.EC_Documents 
        where c.clusterID == _SelectedNode.ID 
        orderby c.clusterID 
        select c; 

     docs.LoadCompleted += (s, e) => 
     { 
      if (e.Error == null) 
      { 
       if (docs.Continuation != null) 
       { 
        docs.LoadNextPartialSetAsync(); 
       } 
       else 
       { 
        cluster.Value = docs.Count; 
       } 
      } 
     };  

    docs.LoadAsync(query); 
} 

init现在,多次调用可能每个使用其自己的实例DataServiceCollection<EC_Documents>进行。我不确定你想要对_SelectedNode.ID值做什么,这对我来说看起来是错误的,你应该将该值作为参数传递给init。当然,docs现在是本地的,您需要决定一旦加载了群集ID的所有文档后,该如何使用它。

+0

谢谢!工作很好! – Gil

+0

让我们复杂一点。比方说,我需要结果是在递归中,每个cluster.Value应该传递给init方法来累积。你会怎么做? – Gil