private StockCalculation Calculate(IEnumerable <StockPrice> prices)
        {
            #region Start stopwatch
            var calculation = new StockCalculation();
            var watch       = new Stopwatch();
            watch.Start();
            #endregion

            var end = DateTime.UtcNow.AddSeconds(4);

            // Spin a loop for a few seconds to simulate load
            while (DateTime.UtcNow < end)
            {
            }

            #region Return a result
            calculation.Identifier = prices.First().Identifier;
            calculation.Result     = prices.Average(s => s.Open);

            watch.Stop();

            calculation.TotalSeconds = watch.Elapsed.Seconds;

            return(calculation);

            #endregion
        }
예제 #2
0
        private async void Search_Click(object sender, RoutedEventArgs e)
        {
            #region Before loading stock data
            var watch = new Stopwatch();
            watch.Start();
            StockProgress.Visibility      = Visibility.Visible;
            StockProgress.IsIndeterminate = true;

            Search.Content = "Cancel";
            #endregion

            #region Cancellation
            if (cancellationTokenSource != null)
            {
                cancellationTokenSource.Cancel();
                cancellationTokenSource = null;
                return;
            }

            cancellationTokenSource = new CancellationTokenSource();

            cancellationTokenSource.Token.Register(() =>
            {
                Notes.Text += "Cancellation requested" + Environment.NewLine;
            });
            #endregion

            try
            {
                #region Load One or Many Tickers
                var tickers = Ticker.Text.Split(',', ' ');

                var service = new StockService();

                var tickerLoadingTasks = new List <Task <IEnumerable <StockPrice> > >();
                foreach (var ticker in tickers)
                {
                    var loadTask = service.GetStockPricesFor(ticker, cancellationTokenSource.Token);

                    tickerLoadingTasks.Add(loadTask);
                }
                #endregion

                var loadedStocks = await Task.WhenAll(tickerLoadingTasks);

                var values = new ConcurrentBag <StockCalculation>();

                var executioResult = Parallel.ForEach(loadedStocks, new ParallelOptions {
                    MaxDegreeOfParallelism = 2
                }, (stocks, state) => {
                    var ticker = stocks.First().Ticker;

                    Debug.WriteLine($"Start processing-->{ticker}");

                    if (ticker == "MSFT")
                    {
                        Debug.WriteLine($"Found {ticker}, breaking");

                        state.Break();

                        return;
                    }

                    if (state.IsStopped)
                    {
                        return;
                    }


                    var result = CalculateExpensiveComputation(stocks);

                    var data = new StockCalculation
                    {
                        Ticker = stocks.First().Ticker,
                        Result = result
                    };

                    values.Add(data);
                });


                Stocks.ItemsSource = values.ToArray();
            }
            catch (Exception ex)
            {
                Notes.Text += ex.Message + Environment.NewLine;
            }
            finally
            {
                cancellationTokenSource = null;
            }

            #region After stock data is loaded
            StocksStatus.Text        = $"Loaded stocks for {Ticker.Text} in {watch.ElapsedMilliseconds}ms";
            StockProgress.Visibility = Visibility.Hidden;
            Search.Content           = "Search";
            #endregion
        }
예제 #3
0
        private async void Search_Click(object sender, RoutedEventArgs e)
        {
            #region Before loading stock data
            var watch = new Stopwatch();
            watch.Start();
            StockProgress.Visibility      = Visibility.Visible;
            StockProgress.IsIndeterminate = true;

            Search.Content = "Cancel";
            #endregion

            #region Cancellation
            if (cancellationTokenSource != null)
            {
                cancellationTokenSource.Cancel();
                cancellationTokenSource = null;
                return;
            }

            cancellationTokenSource = new CancellationTokenSource();

            cancellationTokenSource.Token.Register(() =>
            {
                Notes.Text += "Cancellation requested" + Environment.NewLine;
            });
            #endregion

            try
            {
                #region Load One or Many Tickers
                var tickers = Ticker.Text.Split(',', ' ');

                var service = new StockService();

                var tickerLoadingTasks = new List <Task <IEnumerable <StockPrice> > >();
                foreach (var ticker in tickers)
                {
                    var loadTask = service.GetStockPricesFor(ticker, cancellationTokenSource.Token);

                    tickerLoadingTasks.Add(loadTask);
                }
                #endregion

                var loadedStocks = await Task.WhenAll(tickerLoadingTasks);

                // it will block out the ui
                // it will never begin nor complete in order
                // same for Paraller.Foreach
                // Parallel.For
                // Blocks UI Thread
                #region Intro Paraller Extention
                //Parallel.Invoke(() =>
                //{
                //    Debug.WriteLine("Starting operation 1");

                //    CalculateExpensiveComputation(loadedStocks);

                //    Debug.WriteLine("Completed operation 1");

                //    // if we use dispatcher like the Task lib it will DEADLOCK
                //    //Dispatcher.Invoke(() =>
                //    //{

                //    //});

                //},
                //()=>{
                //    Debug.WriteLine("Starting operation 2");

                //    CalculateExpensiveComputation(loadedStocks);

                //    Debug.WriteLine("Completed operation 2");

                //},
                //()=>{
                //    Debug.WriteLine("Starting operation 3");

                //    CalculateExpensiveComputation(loadedStocks);

                //    Debug.WriteLine("Completed operation 3");

                //},
                //()=>{
                //    Debug.WriteLine("Starting operation 4");

                //    CalculateExpensiveComputation(loadedStocks);

                //    Debug.WriteLine("Completed operation 4");

                //});
                #endregion

                var values = new ConcurrentBag <StockCalculation>();
                Parallel.ForEach(loadedStocks, (stocks) =>
                {
                    var data = new StockCalculation
                    {
                        Result = CalculateExpensiveComputation(stocks),
                        Ticker = stocks.First().Ticker
                    };

                    values.Add(data);
                });
                Stocks.ItemsSource = values.ToArray();
            }
            catch (Exception ex)
            {
                Notes.Text += ex.Message + Environment.NewLine;
            }
            finally
            {
                cancellationTokenSource = null;
            }

            #region After stock data is loaded
            StocksStatus.Text        = $"Loaded stocks for {Ticker.Text} in {watch.ElapsedMilliseconds}ms";
            StockProgress.Visibility = Visibility.Hidden;
            Search.Content           = "Search";
            #endregion
        }
        private async void Search_Click(object sender, RoutedEventArgs e)
        {
            using (var client = new HttpClient())
            {
                try
                {
                    var response = await client.GetAsync("http://localhost:61363");
                }
                catch (Exception)
                {
                    MessageBox.Show("Ensure that StockAnalyzer.Web is running, expecting to be running on http://localhost:61363. You can configure the solution to start two projects by right clicking the StockAnalyzer solution in Visual Studio, select properties and then Mutliuple Startup Projects.", "StockAnalyzer.Web IS NOT RUNNING");
                }
            }

            #region Before loading stock data
            var watch = new Stopwatch();
            watch.Start();
            StockProgress.Visibility      = Visibility.Visible;
            StockProgress.IsIndeterminate = true;

            Search.Content = "Cancel";
            #endregion

            #region Cancellation
            if (cancellationTokenSource != null)
            {
                cancellationTokenSource.Cancel();
                cancellationTokenSource = null;
                return;
            }

            cancellationTokenSource = new CancellationTokenSource();

            cancellationTokenSource.Token.Register(() =>
            {
                Notes.Text += "Cancellation requested" + Environment.NewLine;
            });
            #endregion

            try
            {
                #region Load One or Many Tickers
                var tickers = Ticker.Text.Split(',', ' ');

                var service = new StockService();

                var tickerLoadingTasks = new List <Task <IEnumerable <StockPrice> > >();
                foreach (var ticker in tickers)
                {
                    var loadTask = service.GetStockPricesFor(ticker, cancellationTokenSource.Token);

                    tickerLoadingTasks.Add(loadTask);
                }
                #endregion

                var loadedStocks = await Task.WhenAll(tickerLoadingTasks);

                var values = new ConcurrentBag <StockCalculation>();

                var executionResult = Parallel.ForEach(loadedStocks,
                                                       new ParallelOptions {
                    MaxDegreeOfParallelism = 2
                },
                                                       (stocks, state) =>
                {
                    var ticker = stocks.First().Ticker;

                    Debug.WriteLine($"Start processing {ticker}");

                    if (ticker == "MSFT")
                    {
                        Debug.WriteLine($"Found {ticker}, breaking");

                        state.Stop();

                        return;
                    }

                    if (state.IsStopped)
                    {
                        return;
                    }

                    var result = CalculateExpensiveComputation(stocks);

                    var data = new StockCalculation
                    {
                        Ticker = ticker,
                        Result = result
                    };

                    values.Add(data);

                    Debug.WriteLine($"Completed processing {ticker}");
                });

                Notes.Text  = $"Ran to complation: {executionResult.IsCompleted}" + Environment.NewLine;
                Notes.Text += $"Lowest break iteration: {executionResult.LowestBreakIteration}";

                Stocks.ItemsSource = values.ToArray();
            }
            catch (Exception ex)
            {
                Notes.Text += ex.Message + Environment.NewLine;
            }
            finally
            {
                cancellationTokenSource = null;
            }

            #region After stock data is loaded
            StocksStatus.Text        = $"Loaded stocks for {Ticker.Text} in {watch.ElapsedMilliseconds}ms";
            StockProgress.Visibility = Visibility.Hidden;
            Search.Content           = "Search";
            #endregion
        }