public void CalculateAverageWithDelays()
        {
            var northSales = Enumerable.Empty <CarSale>();
            var eastSales  = new[]
            {
                new CarSale("Ford", 1000D),
                new CarSale("Audi", 2000D),
                new CarSale("Renault", 3000D),
                new CarSale("BMW", 3000D)
            };
            var southSales = new[]
            {
                new CarSale("Fiat", 500D),
                new CarSale("Tesla", 10000D),
                new CarSale("Mercedes", 8000D)
            };
            var westSales = new[]
            {
                new CarSale("Porsche", 6000D)
            };

            var allSales = new[]
            {
                northSales, eastSales,
                southSales, westSales
            };

            var random = new Random();

            var loaders = allSales
                          .Select(sales => new TestSalesLoader(sales, random.Next(3)))
                          .ToList();

            var expectedAverage = allSales
                                  .SelectMany(sales => sales)
                                  .Average(car => car.SalePrice);

            var maxDelay = loaders.Max(ldr => ldr.DelayInSeconds);

            var averageTask  = SalesAggregator.Average(loaders);
            var hasCompleted = averageTask.Wait(TimeSpan.FromSeconds(maxDelay + 2D));

            Assert.IsTrue(hasCompleted);

            //var actualAverage = SalesAggregator.Average(loaders).Result;
            var actualAverage = averageTask.Result;

            Assert.AreEqual(expectedAverage, actualAverage);
        }
Exemplo n.º 2
0
        public static void Main()
        {
            var       random       = new Random();
            const int MaxSalesHubs = 10;

            string input;

            do
            {
                Console.WriteLine("Max wait time (in seconds):");
                input = Console.ReadLine();

                if (string.IsNullOrEmpty(input))
                {
                    continue;
                }

                if (int.TryParse(input, NumberStyles.Any, CultureInfo.CurrentCulture, out var maxDelay))
                {
                    var loaders = Enumerable.Range(1, random.Next(1, MaxSalesHubs))
                                  .Select(n => new SalesLoader(n, random))
                                  .ToList();

                    var averageTask  = SalesAggregator.Average(loaders);
                    var hasCompleted = averageTask.Wait(TimeSpan.FromSeconds(maxDelay));
                    var average      = averageTask.Result;

                    if (hasCompleted)
                    {
                        Logger.Log($"Average={average:N0}");
                    }
                    else
                    {
                        Logger.Log("Timeout!");
                    }
                }
            } while (input != string.Empty);
        }