本文介绍了这两个使用IQueryable和.AsParallel等效的代码片段吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一些非常基本的TPL代码,并且遇到以下情况,我想知道以下两个片段是否相等:

I am working on some pretty basic TPL code, and I ran across a situation where I was curious if the following two snippets are equivalent:

myEnumerable.AsParallel().Select(e =>
{
    //do some work that takes awhile
    return new Thing(e);
}

myEnumerable.Select(e =>
{
    //do some work that takes awhile
    return new Thing(e);
}.AsParallel()

还-如果它们实际上是等效的,它们的等效性是否可以根据IEnumerable扩展方法的TPL接口定义而改变?还是我只是设置自己以在更新到.NET V {What}时破坏代码?

Also - if they are, in fact, equivalent, is their equivalency something that can change as defined by the TPL interface with IEnumerable extension methods? Or am I just setting myself up to break my code when I update to .NET V{Whatever}?

对于背景,myEnumerable是我尚未枚举(使数据库往返)的EF表(实体).

For background, myEnumerable is an EF table (entity) that I have not yet enumerated (made the DB round trip) on.

我想要的行为是同步进行DB调用,取回List,然后对列表进行并行操作(在List上并行进行一堆Web服务调用)

My desired behavior is for the DB call to be made synchronously, get a List back, and operate upon the list in parallel (make a bunch of web service calls on the List in parallel)

推荐答案

不,不是.您先前的代码将尝试 分区IEnumerable以便并行执行.您后面的代码将元素依次投影到Select,并接收过滤后的IEnumerable.只有AsParallel之后的内容才能并行运行.

No, they aren't. Your former code will attempt to partition the IEnumerable in order to execute it in parallel. You latter code will project elements to your Select sequentially, and receive the filtered IEnumerable. Only what comes after the AsParallel will run in parallel.

请注意,LINQ-To-Entities不适用于AsParallel.通常,它会使您的代码运行缓慢,然后顺序运行.另外,DbContext也不是线程安全的.该代码可能会造成更多的伤害,然后再带来好处.

Note that LINQ-To-Entities doesn't really work with AsParallel. Usually, it will cause your code to run slower then it will sequentially. Also, DbContext is not thread-safe. That code will potentially cause more harm then good.

您可以做的是先查询数据库,然后将数据存储在内存中,然后使用AsParallel.

What you can do is first query the database, and once the data is in-memory, use AsParallel.

如果要通过返回的数据进行多个Web服务调用,则可以利用存在的自然异步API发出此类请求.例如,如果您要查询HTTP端点,则可以利用HttpClient并将其与async-await结合使用,并发执行查询,而无需任何额外的线程.

If you want to make multiple web service calls via the returned data, you can take advantage of the natural async API that exists for making such requests. For example, if you're querying an HTTP endpoint, you can exploit HttpClient and use it in combination with async-await, and execute queries concurrently, without needing any extra threads.

这篇关于这两个使用IQueryable和.AsParallel等效的代码片段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 00:44