public static void SellCookieTo(Person customer) { if (Cookies.Count <= cookiesSold) return; // Nuh-uh lock (Cookies[cookiesSold++]) { Console.WriteLine("\t\t\t\t" + customer.Name + " received cookie #" + cookiesSold); } }
private static void GrabTed() { var ted = new Person("Ted"); var stopwatch = new Stopwatch(); stopwatch.Start(); while (CookieBakery.DailyQuotaNotSold) { if (stopwatch.ElapsedMilliseconds < BuyingTimeMilliseconds) continue; CookieBakery.SellCookieTo(ted); stopwatch.Restart(); } }
/// <summary> /// "Sells" a cookie to the customer by incrementing the number of cookies /// sold. Makes sure each cookie can only be sold once by locking the list. /// </summary> /// <param name="customer">The customer attempting to grab the cookie.</param> public static void SellCookieTo(Person customer) { lock (BakedCookies) { // Can't sell cookies that don't exist if (BakedCookies.Count <= cookiesSold) { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("\t\t\t\tNo cookie for {0}", customer.Name); return; } // Printing and THEN updating so Program's "monitor" won't mistakenly // "think" all cookies have been sold until the line has been printed Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(customer.Name + " grabbed cookie #{0}", ++cookiesSold); } }