Ejemplo n.º 1
0
        private async Task <decimal> FetchPricesParallelAsync(IEnumerable <StockHolding> holdings)
        {
            decimal totalWorth = 0m;

            var tasks = holdings.Select(
                async holding => new { holding,
                                       price = await priceService.LookupPriceAsync(holding.Ticker) })
                        .ToList();

            foreach (var task in tasks.InCompletionOrder())
            {
                var result  = await task;
                var holding = result.holding;
                var price   = result.price;
                Log("Price of {0}: {1}", holding.Ticker, price);

                AddPortfolioEntry(
                    holding.Ticker, holding.Quantity,
                    price, holding.Quantity * price);
                if (price != null)
                {
                    totalWorth += holding.Quantity * price.Value;
                }
            }
            return(totalWorth);
        }
Ejemplo n.º 2
0
        private async Task <decimal> CalculateWorthAsyncImpl(string user, string password)
        {
            var userId = await authenticationService.AuthenticateUserAsync(user, password);

            if (userId == null)
            {
                throw new AuthenticationException("Bad username or password");
            }

            var portfolio = await portfolioService.GetPortfolioAsync(userId.Value);

            decimal total = 0m;

#if !PARALLEL
            #region Serial implementation
            foreach (var item in portfolio)
            {
                var price = await priceService.LookupPriceAsync(item.Ticker);

                if (price != null)
                {
                    total += price.Value * item.Quantity;
                }
            }
            #endregion
#else
            #region Parallel implementation
            var tasks = portfolio.Select(async holding => new
            {
                holding,
                price = await priceService.LookupPriceAsync(holding.Ticker)
            }).ToList();

            foreach (var task in tasks.InCompletionOrder())
            {
                var result  = await task;
                var holding = result.holding;
                var price   = result.price;
                if (price != null)
                {
                    total += holding.Quantity * price.Value;
                }
            }
            #endregion
#endif
            return(total);
        }