Esempio n. 1
0
        private async Task FetchStocksAsync()
        {
            try
            {
                fetchButton.Enabled = false;

                Log("Authenticating");
                Task <Guid?> authTask = authenticationService.AuthenticateUserAsync
                                            (userTextBox.Text, passwordTextBox.Text);
                Log("Authentication started");
                Guid?userId = await authTask;

                Log("Authenticated - GUID={0}", userId);
                if (userId == null)
                {
                    Log("Authentication failure - abort.");
                    MessageBox.Show("User unknown, or incorrect password",
                                    "Authentication failure",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                Log("Fetching holdings");
                List <StockHolding> holdings =
                    await portfolioService.GetPortfolioAsync(userId.Value);

                Log("Received {0} holdings", holdings.Count);

                Log("Fetching prices");
                decimal totalWorth = await FetchPricesParallelAsync(holdings);

                Log("Fetched all prices");
                AddPortfolioEntry("TOTAL", null, null, totalWorth);
            }
            finally
            {
                fetchButton.Enabled = true;
            }
        }
Esempio 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);
        }