Beispiel #1
0
        public string ServeCustomer(StockController_WithConcurrent controller)
        {
            Thread.Sleep(Rnd.NextInt(5));
            TShirt shirt = TShirtProvider.SelectRandomShirt();
            string code  = shirt.Code;

            //assuming customer will always buy/sell a shirt
            bool custSells = Rnd.TrueWithProb(1.0 / 6.0);          //customer want to sell a shirt 1/6th of the time

            if (custSells)
            {
                int quantity = Rnd.NextInt(9) + 1;
                controller.BuyShirts(code, quantity);
                return($"Bought {quantity} of {shirt}");
            }
            else
            {
                bool success = controller.TrySellShirt(code);
                if (success)
                {
                    return($"Sold {shirt}");
                }
                else
                {
                    return($"Couldn't sell {shirt}: Out of stock");
                }
            }
        }
        public static void Run()
        {
            //StockController controller = new StockController();
            //TimeSpan workDay = new TimeSpan(0, 0, 0, 0, 500);

            //new SalesPerson("Jack").Work(workDay, controller);
            //new SalesPerson("Anna").Work(workDay, controller);
            //new SalesPerson("Bond").Work(workDay, controller);

            //controller.DisplayStock();


            StockController_WithConcurrent controller = new StockController_WithConcurrent();
            TimeSpan workDay = new TimeSpan(0, 0, 0, 0, 500);

            Task task1 = Task.Run(() => new SalesPerson_Concurrent("Jack").Work(workDay, controller));
            Task task2 = Task.Run(() => new SalesPerson_Concurrent("Anna").Work(workDay, controller));
            Task task3 = Task.Run(() => new SalesPerson_Concurrent("Bond").Work(workDay, controller));
            Task task4 = Task.Run(() => new SalesPerson_Concurrent("Kim").Work(workDay, controller));

            Task.WaitAll(task1, task2, task3, task4);

            controller.DisplayStock();
            //---------CONCURRENT DICTIONARY METHODS------------
            //       AddOrUpdate()           |            GetOrAdd()
            // Solution for updating         |    solution for reading
            //Guarenteed to succeed          |		Guarenteed to succeed
            //Add item if not already there  |    Adds the item if it's not there
        }
Beispiel #3
0
        public void Work(TimeSpan workDay, StockController_WithConcurrent controller)
        {
            DateTime start = DateTime.Now;

            while (DateTime.Now - start < workDay)
            {
                string msg = ServeCustomer(controller);
                if (msg != null)
                {
                    Console.WriteLine($"{Name}: {msg}");
                }
            }
        }