AsParallel()和Any()? [英] AsParallel () and Any()?

查看:169
本文介绍了AsParallel()和Any()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过这段代码,它使用 AsParallel() Any()检查条件:

I've seen this code which check a condition using AsParallel() and Any() :

bool IsAnyDeviceConnected()
{
   return m_devices.Any(d => d.IsConnected);
}

并使其变得更快:

bool IsAnyDeviceConnected()
{
   return m_devices.AsParallel().Any(d => d.IsConnected);
}

但查看 Any()

 internal static bool Any<T>(this IEnumerable<T> source, Func<T, bool> predicate) {
            foreach (T element in source) {
                if (predicate(element)) {
                    return true;
                }
            }
            return false;
        }

我没看到(很明显)-它确实关心取消其他工作人员-一旦找到

I don't see (obviously) - that it does care about cancellation of other workers - once found.

但是-此( other )代码确实完成-尽快 +取消其他以后的工作:

However - this (other) code does "finish - soon as possible" + cancel other future work :

bool IsAnyDeviceConnected()
{
   var res = Parallel.ForEach(m_devices,
      (d,loopState) => {  
         if (d.IsConnected) 
            loopState.Stop();
      });
   return !res.IsCompleted;
}

问题:

我的诊断是否正确?是否 Any()-一旦找到了项目,就不会取消其他线程(在AsParallel上下文中)

Does my diagnostics correct? Does Any() - once found item , doesn't cancel other threads ( in AsParallel context)

nb,我担心我会看错源代码。

推荐答案

AsParallel() 返回 ParallelQuery ,因此,如果调用 AsParallel()。Any(...)不会调用< a href = http://msdn.microsoft.com/en-us/library/vstudio/bb337697(v=vs.100).aspx> Enumerable.Any ,但 ParallelEnumerable.Any

AsParallel() returns a ParallelQuery, so if you call AsParallel().Any(...) you're not calling Enumerable.Any, but ParallelEnumerable.Any.

ParallelEnumerable.Any 的参考源代码为此处

例如进入 AnyAllSearchOperatorEnumerator 类,您会看到一个名为 resultFoundFlag 的标志用于告诉其他工作人员发现了结果,所以它们可以停止搜索

When you dig e.g. into the AnyAllSearchOperatorEnumerator class, you see that a flag called resultFoundFlag is used to tell other workers that a result is found so they can stop searching.

这篇关于AsParallel()和Any()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆