同时加载多个 RIA 服务查询
我想做类似于下面的事情,我为每个已加载实体的集合并行加载一些相关数据:
foreach (var parentThing in ParentThings)
{
Context.Load(Context.GetChildThingForParentQuery(parentThing.Id), op =>
{
parentThing.Child = op.Entities.FirstOrDefault();
}, null);
}
但是,它似乎不起作用。数据在回调 lambda 中混合在一起,例如,parentThing 始终是集合中的最后一个对象,而 op.Entities 始终仅包含第一个子对象。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
foreach
的问题是由访问修改后的闭包引起的。尝试:The problem with your
foreach
is caused by accessing a modified closure. Try:这样想吧,因为收到回调的时间是异步的,foreach循环早已通过了当前的parentThing,这就是为什么你会得到混合结果(Lemans术语,我相信其他人能够给你一个对此有更好的答案)。
我过去见过最好逐个触发它们并在继续之前等待第一个结果,这样您就可以将最后触发的parentThing保留在全局变量或类似的变量中,并且您将收到正确的子实体。
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.