LINQ:如何根据上下文修改 AsParallel 的返回类型?
LINQ 的 AsParallel
返回 ParallelQuery
。我想知道是否可以更改此行为,以便我可以比较使用并行性和不使用并行性运行的 LINQ 语句,而无需实际更改代码?此行为应该类似于 Debug.Assert - 当未设置 DEBUG 预处理器指令时,它会被优化。因此,我希望能够使 AsParallel
返回相同的类型,而无需将其转换为 ParallelQuery
。
我想我可以声明我自己的扩展方法(因为我无法重写 AsParallel)并在其中分析预处理器指令:
public static class MyExtensions
{
#if TURN_OFF_LINQ_PARALLELISM
public static IEnumerable<T> AsControllableParallel<T>(this IEnumerable<T> enumerable)
{
return enumerable;
}
#else
public static ParallelQuery<T> AsControllableParallel<T>(this IEnumerable<T> enumerable)
{
return enumerable.AsParallel();
}
#endif
}
我想知道是否还有其他方法。我的要求是不是太多了?
LINQ's AsParallel
returns ParallelQuery
. I wonder if it's possible to change this behavior so that I could compare the LINQ statement run with and without parallelism without actually changing the code? This behavior should be similar to Debug.Assert
- when DEBUG
preprocessor directive is not set, it's optimized out. So I'd like to be able to make AsParallel
return the same type without converting it to ParallelQuery
.
I suppose I can declare my own extension method (because I can't override AsParallel
) and have that preprocessor directive analyzed within it:
public static class MyExtensions
{
#if TURN_OFF_LINQ_PARALLELISM
public static IEnumerable<T> AsControllableParallel<T>(this IEnumerable<T> enumerable)
{
return enumerable;
}
#else
public static ParallelQuery<T> AsControllableParallel<T>(this IEnumerable<T> enumerable)
{
return enumerable.AsParallel();
}
#endif
}
I wonder if there is any other way. Am I asking for too much?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
怎么样
What about
您可以创建自己的扩展方法,并将这些方法转发到发布版本中的“真正的”AsParallel 方法,并在调试版本中使用顺序方法。通过检查当前命名空间中的方法来解析扩展方法,然后搜索“外部”命名空间(仍然首选实例方法)。
You can create your own extension methods and forward these to the "real" AsParallel method in release builds and use the sequential ones in debug builds. Extension methods are resolved by checking for method in the current namespace and then are the "outer" namespaces searched (instance methods are still preferred).