예제 #1
0
        // This event handler updates the ListView control when the
        // PrimeNumberCalculator raises the ProgressChanged event.
        //
        // On fast computers, the PrimeNumberCalculator can raise many
        // successive ProgressChanged events, so the user interface
        // may be flooded with messages. To prevent the user interface
        // from hanging, progress is only reported at intervals.
        private void primeNumberCalculator1_ProgressChanged(
            ProgressChangedEventArgs e)
        {
            if (e is CalculatePrimeProgressChangedEventArgs)
            {
                CalculatePrimeProgressChangedEventArgs cppcea =
                    e as CalculatePrimeProgressChangedEventArgs;

                Console.WriteLine("# {0}%  Now:{1}",
                                  cppcea.ProgressPercentage,
                                  cppcea.LatestPrimeNumber);
            }
            else
            {
                Console.WriteLine("# {0}%",
                                  e.ProgressPercentage);
            }
        }
예제 #2
0
        // This method computes the list of prime numbers used by the
        // IsPrime method.

        /// <summary>
        /// 返回 质数的列表.
        /// </summary>
        /// <param name="numberToTest"></param>
        /// <param name="asyncOp"></param>
        /// <returns></returns>
        private ArrayList BuildPrimeNumberList(
            int numberToTest,
            AsyncOperation asyncOp)
        {
            ProgressChangedEventArgs e = null;
            ArrayList primes           = new ArrayList();
            int       firstDivisor;
            int       n = 5;

            // Add the first prime numbers.
            primes.Add(2);
            primes.Add(3);


            // Do the work.
            // 每次循环,都调用 TaskCanceled 方法,当该方法返回 true 时它就会退出。
            while (n < numberToTest &&
                   !TaskCanceled(asyncOp.UserSuppliedState))
            {
                if (IsPrime(primes, n, out firstDivisor))
                {
                    // Report to the client that a prime was found.
                    e = new CalculatePrimeProgressChangedEventArgs(
                        n,
                        (int)((float)n / (float)numberToTest * 100),
                        asyncOp.UserSuppliedState);

                    asyncOp.Post(this.onProgressReportDelegate, e);

                    primes.Add(n);

                    // Yield the rest of this time slice.
                    Thread.Sleep(0);
                }



                // Skip even numbers.
                // 这里排除掉偶数.
                n += 2;
            }

            return(primes);
        }