user380689
user380689

Reputation: 1794

Loading multiple RIA Services queries at same time

I want to do something similar to below where I am loading in parallel some related data for each of a collection of already loaded entities:

    foreach (var parentThing in ParentThings)
    {
        Context.Load(Context.GetChildThingForParentQuery(parentThing.Id), op =>
            {
                parentThing.Child = op.Entities.FirstOrDefault();
            }, null);
    }

However, it doesn't seem to work. Data is all mixed up in the callback lambda, e.g. parentThing is always the LAST object in the collection and op.Entities always contains only the FIRST child.

Upvotes: 1

Views: 525

Answers (2)

Ed Chapel
Ed Chapel

Reputation: 6932

The problem with your foreach is caused by accessing a modified closure. Try:

foreach (var temp in ParentThings) 
{
    var parentThing = temp;
    Context.Load(Context.GetChildThingForParentQuery(parentThing.Id), op =>
        {
            parentThing.Child = op.Entities.FirstOrDefault();
        }, null);
}

Upvotes: 1

TBohnen.jnr
TBohnen.jnr

Reputation: 5119

Think of it this way, because it's asynchronious the time the callback is received the foreach loop has long since passed the current parentThing and this is why you are getting mixed results (Lemans terms, I am sure somebody else will be able to give you a better answer with regards to this).

I have seen in the past it's best to fire these off one by one and wait for the first result before continuing, that way you can keep the last fired parentThing in a global variable or something similar and you will receive back the correct child entity.

    int counter = 0;
    object lastParentThing;

    protected void loopParentThings()
    {
        lastParentThing = ParentThings[counter];
        counter++;

        Context.Load(Context.GetChildThingForParentQuery(lastParentThing.Id), op =>
        {
            lastParentThing.Child = op.Entities.FirstOrDefault();
            loopParentThings()
        }, 
        null);
    }

Upvotes: 1

Related Questions