Exemple #1
0
        private static async Task <long[]> ProcessFibonacciWithTasks(long[] fibonacciNumbers, int numberOfTasks, ProcessingType processingType)
        {
            var tasks = new List <Task>(numberOfTasks);

            for (int i = 0; i < numberOfTasks; i++)
            {
                int taskIndex = i; //concurrency workaround for captured vars
                var task      = new Task(() => CalculateFibonacci(fibonacciNumbers, numberOfTasks, taskIndex, processingType));
                tasks.Add(task);
            }

            var watch = Stopwatch.StartNew();

            tasks.ForEach(x => x.Start());
            await Task.WhenAll(tasks);

            watch.Stop();

            Console.WriteLine($"{numberOfTasks} Threads: {watch.ElapsedMilliseconds} milliseconds");

            var numbers = ConcurrentStore.GetSortedNumbersFromStore();

            ConcurrentStore.ClearStore();

            return(numbers);
        }
Exemple #2
0
        public void GetOrAdd_TryAddOneHundredRecords_AddsOnlyOneRecord()
        {
            var store = new ConcurrentStore <int, object>();

            Parallel.ForEach(Enumerable.Repeat(1, 100), i =>
            {
                store.GetOrAdd(i, x => new object());
            });

            store.Count.Should().Be(1);
        }
Exemple #3
0
        public static void AddNumberAndCheckIfIsDone(long number)
        {
            ConcurrentStore.AddNumberToStore(number);
            Interlocked.Increment(ref _numbersProcessed);

            if (_numbersProcessed >= _numbersToProcess)
            {
                _stopWatch.Stop();
                Console.WriteLine($"{_stopWatch.ElapsedMilliseconds} milliseconds");

                var result = ConcurrentStore.GetSortedNumbersFromStore();
                FileUtility.WriteNumbersToFile(OUTPUT_FILE, result);

                ConcurrentStore.ClearStore();
                _numbersProcessed = 0;
            }
        }
Exemple #4
0
        private static void CalculateFibonacci(long[] fibonacciNumbers, int numberOfTasks, int taskIndex, ProcessingType processingType)
        {
            var fibonacciCalculator = new FibonacciCalculator();
            int numbersPerTask      = fibonacciNumbers.Length / numberOfTasks; // ideal case, even tasks and even numbers count
            int numbersToProcess    = 0;

            if (taskIndex == numberOfTasks - 1) // if is last task
            {
                numbersToProcess = fibonacciNumbers.Length - (numbersPerTask * (numberOfTasks - 1));
            }
            else
            {
                numbersToProcess = numbersPerTask;
            }

            for (int i = 0; i < numbersToProcess; i++)
            {
                var numberIndex = taskIndex * numbersPerTask + i;
                var result      = fibonacciCalculator.Calculate(fibonacciNumbers[numberIndex], processingType);
                ConcurrentStore.AddNumberToStore(result);
            }
        }