Пример #1
0
        public static List <long> GetPrimesParallel(long first, long last)
        {
            var lockObject            = new object();
            IEnumerable <long> result = new List <long>();

            Parallel.ForEach(
                Partitioner.Create(first, last),
                () => new List <long>(),
                (range, loopState, partialResult) =>
            {
                for (long i = range.Item1; i < range.Item2; i++)
                {
                    if (PrimeTool.IsPrime(i))
                    {
                        partialResult.Add(i);
                    }
                }

                return(partialResult);
            },
                (partialResult) =>
            {
                lock (lockObject)
                {
                    result = result.Concat(partialResult);
                }
            }
                );
            return(result.OrderBy(s => s).ToList());
        }