开发者

Get asynchronous data from wcf service

I have a wcf which retrieves information from a database.

I also have a Silverlight client application which references that service and uses it to retrieve the data.

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;

            }
        }
    }

Because the call is asynchronous, I had to make docs a member of the class and check its count at the docs_LoadCompleted method.

I also have a _SelectedCluster which is an object of type Cluster as a member in the class,which holds the current cluster object in the iteration.

I have a problem assigning the result to the currently selected node _SelectedCluster.Value member.

Because the call is asynchronous, I cannot iterate on all my clusters objects and assign the result synchronously, If I do that, the assignment is always on the last cluster in the iteration.

Any suggestions?


Re-arrange your code to benefit from closures:-

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);
}

Now multiple calls to init can be made each using its own instance DataServiceCollection<EC_Documents>. I'm not sure what you want to do about the _SelectedNode.ID value that looks wrong to me, you ought to be passing that value in as a parameter on the init. Of course with docs now being local you will need to decide what to with it once all the docs for a cluster ID is loaded.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜