Example #1
0
        private void Search_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                BeforeLoadingStockData();

                var loadLinesTask = Task.Run(() => {
                    // This code now runs in a separate thread
                    var lines = File.ReadAllLines("StockPrices_Small.csv");

                    return(lines);
                });

                var processStocksTask = loadLinesTask.ContinueWith(completedTask =>
                {
                    var lines = completedTask.Result;

                    var data = new List <StockPrice>();

                    foreach (var line in lines.Skip(1))
                    {
                        var price = StockPrice.FromCSV(line);

                        data.Add(price);
                    }

                    // this allows us to pass our code into UI thread for execution
                    Dispatcher.Invoke(() =>
                    {
                        // Warning, do not do here anything heavy or anything that might block the UI thread.
                        Stocks.ItemsSource = data.Where(sp => sp.Identifier == StockIdentifier.Text);
                    });
                });

                processStocksTask.ContinueWith(_ => {
                    Dispatcher.Invoke(() => {
                        AfterLoadingStockData();
                    });
                });
            }
            catch (Exception ex)
            {
                Notes.Text = ex.Message;
            }
            finally
            {
            }
        }
Example #2
0
        private static Task <IEnumerable <StockPrice> > SearchForStocks()
        {
            var tcs = new TaskCompletionSource <IEnumerable <StockPrice> >();

            ThreadPool.QueueUserWorkItem(_ => {
                var lines  = File.ReadAllLines("StockPrices_Small.csv");
                var prices = new List <StockPrice>();

                foreach (var line in lines.Skip(1))
                {
                    prices.Add(StockPrice.FromCSV(line));
                }
                tcs.SetResult(prices);      // Communicates the task should be set to completedx.
            });

            return(tcs.Task);
        }
Example #3
0
        public async IAsyncEnumerable <StockPrice> GetAllStockPrices([EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            using var stream = new StreamReader(File.OpenRead("StockPrices_Small.csv"));

            await stream.ReadLineAsync(); // Skipping header row

            string line;

            while ((line = await stream.ReadLineAsync()) != null)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                yield return(StockPrice.FromCSV(line));
            }
        }