コード例 #1
0
        // Using ThreadStart delegate
        private static void UsingThreadStartDelegate()
        {
            Console.WriteLine("***** The Amazing Thread App *****\n");
            Console.Write("Do you want [1] or [2] threads? ");
            string threadCount = Console.ReadLine();

            // Name the current thread.
            Thread primaryThread = Thread.CurrentThread;

            primaryThread.Name = "Primary";

            // Display Thread info.
            Console.WriteLine("-> {0} is executing Main()",
                              Thread.CurrentThread.Name);

            // Make worker class.
            Threading.Printer p = new Threading.Printer();

            switch (threadCount)
            {
            case "2":
                // Now make the thread.
                Thread backgroundThread = new Thread(new ThreadStart(p.PrintNumbers))
                {
                    Name = "Secondary"
                };
                backgroundThread.Start();
                break;

            case "1":
                p.PrintNumbers();
                break;

            default:
                Console.WriteLine("I don't know what you want...you get 1 thread.");
                goto case "1";
            }

            // Do some additional work.
            MessageBox.Show("I'm busy!", "Work on main thread...");
        }
コード例 #2
0
        // Create concurrency and then solve concurrency using lock keyword and Monitor type
        private static void Concurrency()
        {
            Console.WriteLine("*****Concurrency & Synchronizing Threads *****\n");
            Threading.Printer p = new Threading.Printer();

            // Make 10 threads that are all pointing to the same
            // method on the same object.
            Thread[] threads = new Thread[10];
            for (int i = 0; i < 10; i++)
            {
                //threads[i] = new Thread(new ThreadStart(p.PrintNumbersConcurrency));  // Creates concurrency issues.
                //threads[i] = new Thread(new ThreadStart(p.PrintNumbersLock));         // Locks the shared resource using lock keyword.
                threads[i] = new Thread(new ThreadStart(p.PrintNumbersWithMonitor));    // Locks the shared resource using Monitor type which offers
                                                                                        // more control. Check MS SDK documentation for more.
                threads[i].Name = string.Format("Worker thread #{0}", i);
            }


            // Now start each one.
            foreach (Thread t in threads)
            {
                t.Start();
            }
        }