PLINQ Совокупное исключение, я не понимаю - PullRequest
0 голосов
/ 29 июня 2010

Я шел на презентацию PLINQ PCD09 Игоря Островского и хотел посмотреть, что я смогу получить от своего ноутбука CULV.

В какой-то момент я получил странное исключение, и я не уверен, что это значит. Я сжал код для лучшего обзора. Это последнее primes.Sum (), которое вызывает исключение, и, если я уменьшу диапазон - 8000 - исключение не выдается. Есть идеи?

Func<int, bool> isprime = n => // ignore input checks for now
    {
        int sqr = Convert.ToInt32(Math.Ceiling(Math.Sqrt(n)));
        for (int i = 2; i < sqr; i++) if (n % i == 0) return false;
        return true;
    };

var numbers = Enumerable.Range(1, 8*1000*1000);
long counter = 0;
ParallelQuery<int> primes = numbers.AsParallel().Where(x => isprime(x));
counter = primes.Sum();

Исключение (довольно длинное)

System.AggregateException был необработанное сообщение = одна или несколько ошибок произошло. Источник = System.Core
Трассировки стека: at System.Linq.Parallel.QueryTaskGroupState.QueryEnd (Boolean userInitiatedDispose) в System.Linq.Parallel.SpoolingTask.SpoolStopAndGo [TInputOutput, TIgnoreKey] (QueryTaskGroupState groupState, PartitionedStream 2 partitions, SynchronousChannel 1 [] каналы, TaskScheduler TaskScheduler) at System.Linq.Parallel.DefaultMergeHelper 2.System.Linq.Parallel.IMergeHelper<TInputOutput>.Execute() at System.Linq.Parallel.MergeExecutor 1. Выполнить [TKey] (PartitionedStream 2 partitions, Boolean ignoreOutput, ParallelMergeOptions options, TaskScheduler taskScheduler, Boolean isOrdered, CancellationState cancellationState, Int32 queryId) at System.Linq.Parallel.PartitionedStreamMerger 1.Получить [TKey] (PartitionedStream 2 partitionedStream) at System.Linq.Parallel.InlinedAggregationOperator 3.WrapPartitionedStream [TKey] (PartitionedStream 2 inputStream, IPartitionedStreamRecipient 1) получатель, логическое предпочтение Настройки QuerySettings) в System.Linq.Parallel.UnaryQueryOperator 2.UnaryQueryOperatorResults.ChildResultsRecipient.Receive[TKey](PartitionedStream 2 InputStream) в System.Linq.Parallel.WhereQueryOperator 1.WrapPartitionedStream[TKey](PartitionedStream 2 InputStream, IPartitionedStreamRecipient 1 recipient, Boolean preferStriping, QuerySettings settings) at System.Linq.Parallel.UnaryQueryOperator 2.UnaryQueryOperatorResults.ChildResultsRecipient.Receive [TKey] (PartitionedStream 2 inputStream) at System.Linq.Parallel.ScanQueryOperator 1.ScanEnumerableQueryOperatorResults.GivePartitionedStream (IPartitionedStreamRecipient 1 recipient) at System.Linq.Parallel.UnaryQueryOperator 2.UnaryQueryOperatorResults.GivePartitionedStream (IPartitionedStreamRecipient * * 2.UnaryQueryOperatorResults.GivePartitionedStream тысяча двадцать-одина (IPartitionedStreamRecipient * * 1 тысяча двадцать две .GetOpenedEnumerator (Nullable 1 mergeOptions, Boolean suppressOrder, Boolean forEffect, QuerySettings querySettings) at System.Linq.Parallel.QueryOpeningEnumerator 1.OpenQuery () в System.Linq.Parallel.QueryOpeningEnumerator 1.MoveNext() at System.Linq.Parallel.IntSumAggregationOperator.InternalAggregate(Exception& singularExceptionToThrow) at System.Linq.Parallel.InlinedAggregationOperator 3.Aggregate () at System.Linq.ParallelEnumerable.Sum (ParallelQuery 1 source) at ConsoleTest.TestClass.Test() in C:\Users\henrik\Documents\Visual Studio 2010\Projects\CSharp\ConsoleTest\ConsoleTest\TestClass.cs:line 23 at ConsoleTest.Program.Main(String[] args) in C:\Users\henrik\Documents\Visual Studio 2010\Projects\CSharp\ConsoleTest\ConsoleTest\Program.cs:line 20 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: System.OverflowException Message=Arithmetic operation resulted in an overflow. Source=System.Core StackTrace: at System.Linq.Parallel.IntSumAggregationOperator.IntSumAggregationOperatorEnumerator 1.MoveNextCore (Int32 & currentElement) в System.Linq.Parallel.InlinedAggregationOperatorEnumerator 1.MoveNext(TIntermediate& currentElement, Int32& currentKey) at System.Linq.Parallel.StopAndGoSpoolingTask 2.SpoolingWork () в System.Linq.Parallel.SpoolingTaskBase.Work () в System.Linq.Parallel.QueryTask.BaseWork (Object не используется) в System.Linq.Parallel.QueryTask. <. cctor> b__0 (Object о) в System.Threading.Tasks.Task.InnerInvoke () в System.Threading.Tasks.Task.Execute () InnerException:

1 Ответ

5 голосов
/ 29 июня 2010

Если вы удалите вызов AsParallel (), вы увидите, что выбрасывает Enumerable.Sum и OverflowException. Изменение Sum () на Sum (x => (long) x) должно помочь.

...