I've seen this code which check a condition using AsParallel()
and Any()
:
bool IsAnyDeviceConnected()
{
return m_devices.Any(d => d.IsConnected);
}
and to make it faster :
bool IsAnyDeviceConnected()
{
return m_devices.AsParallel().Any(d => d.IsConnected);
}
But looking at 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.
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;
}
Question :
Does my diagnostics correct? Does Any()
- once found item , doesn't cancel other threads ( in AsParallel context)
nb , my fear is that I might looking at the wrong source code.
Enumerable.Any
– Quintic