使用 PLINQ 返回 null
我有一个 IEnumerable 的扩展方法,然后迭代该集合,执行其业务,然后返回一个新的 IEnumerable。
我尝试使用 PLINQ 使用 .AsParallel().ForAll() ,它可以显着加快迭代速度(当然应该这样做),但是当返回集合时,该集合中通常有一些对象为空。
我假设这可能是因为它在所有“业务”有机会完成之前返回集合?如果我调试并设置断点,则没有空值。
我应该使用某种“等待此操作完成”的方法吗?
编辑:更清楚一点,forall 中有业务逻辑,修改属性等。有必要循环操作,而不是简单地选择某些内容。
i have an extension method for IEnumerable which then iterates through the collection, doing its business, and then returns an new IEnumerable.
I have tried to use PLINQ using .AsParallel().ForAll() which speeds up the iterations significantly (which of course it should do) however when the collection is returned, there are often a few objects in that collection that are null.
I'm assuming this may be because it is returning the collection before all the 'business' has a chance to complete? if i debug and put in a breakpoint, there are no nulls.
is there some sort of 'wait for this operation to be completed' method that i should be using?
EDIT: to be a bit clearer, there is business logic in the forall, modifying properties etc. it's necessary to have an action looped, rather than simply selecting something.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
答案取决于返回的含义,因为
ForAll
方法不返回任何内容。它为集合的所有元素并行调用您指定的委托。我假设您的代码如下所示:ForAll
方法不会等待所有委托完成,因此more code
可以在所有委托完成之前执行(并且您还需要小心将结果存储在某处
位,因为它可能会为多个委托同时运行!)我认为可以使用
Select
方法更优雅地重写代码:在这种情况下,委托只是返回结果。
Where
方法收集所有结果,当您迭代返回的IEnumerable
时,它保证所有委托都完成计算。The answer depends on what you mean by returning, because the
ForAll
method doesn't return anything. It invokes the delegate you specify in parallel for all elements of the collection. I would suppose that your code looks like this:The
ForAll
method doesn't wait for all delegates to complete, somore code
can execute before all the delegates complete (and you also need to be careful in thestore result somewhere
bit, because it may run concurrently for multiple delegates!)I think the code could be rewritten more elegantly using the
Select
method:In this case, the delegate simply returns the result. The
Where
method collects all the results and when you iterate over the returnedIEnumerable
, it guarantees that all delegates finished calculating.ForAll()
不执行合并,并立即返回。Parallel.ForEach()
可能是您正在寻找的功能。即而不是:
collection.AsParallel().ForAll( t=>t.doWork() );
类似
Parallel.ForEach(collection.AsParallel(), t=>t .doWork());
ForAll()
doesn't perform a merge, and returns immediately.Parallel.ForEach()
is probably the functionality you're looking for.ie instead of:
collection.AsParallel().ForAll( t=>t.doWork() );
something like
Parallel.ForEach(collection.AsParallel(), t=>t.doWork());