예제 #1
0
        static public void WhiteThread(RedWhiteSynchronizer synchronizer)
        {
            synchronizer.StartWhite();

            for (int i = 0; i < 100; i++)
            {
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("W ");
                Task.Delay(100);
            }

            synchronizer.StopWhite();
        }
예제 #2
0
        static void Main(string[] args)
        {
            RedWhiteSynchronizer rw = new RedWhiteSynchronizer();

            Console.WriteLine("Unsynchronized threads:");
            List <Task> tasks = new List <Task>();

            rw.Enabled = false;
            for (int i = 0; i < 100; i++)
            {
                if (i % 2 == 0)
                {
                    tasks.Add(Task.Run(() => WhiteThread(rw)));
                }
                else
                {
                    tasks.Add(Task.Run(() => RedThread(rw)));
                }
            }

            Task.WaitAll(tasks.ToArray());

            Console.WriteLine("\nPress enter to do synchronized tasks:");
            Console.ReadLine();

            rw.Enabled = true;
            tasks      = new List <Task>();
            rw.Enabled = true;
            for (int i = 0; i < 100; i++)
            {
                if (i % 2 == 0)
                {
                    tasks.Add(Task.Run(() => WhiteThread(rw)));
                }
                else
                {
                    tasks.Add(Task.Run(() => RedThread(rw)));
                }
            }

            Task.WaitAll(tasks.ToArray());
            Console.ReadLine();
        }