1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | using System; using System.Threading; namespace ThreadingApp { public class Program { static void Main( string [] args) { Program program = new Program(); program.RunApp(); Console.ReadKey(); } public void RunApp() { ThreadPool.QueueUserWorkItem(ThreadMethod, "Thread 1" ); ThreadPool.QueueUserWorkItem(ThreadMethod, "Thread 2" ); ThreadMethod( "Thread 3" ); ThreadPool.QueueUserWorkItem(ThreadMethod, "Thread 4" ); Console.WriteLine( "Main thread exits." ); Thread myThread = new Thread( new ThreadStart(ThreadCallback)); myThread.Name = "My Thread" ; myThread.Priority = ThreadPriority.Highest; Console.WriteLine( "From runapp, {0}.ThreadState={1}" , myThread.Name, myThread.ThreadState); myThread.Start(); } void ThreadCallback() { Console.WriteLine( "Calling ThreadCallback" ); Console.WriteLine( "{0}.ThreadState={1}" , Thread.CurrentThread.Name, Thread.CurrentThread.ThreadState); } void ThreadMethod(Object stateInfo) { String state = (String) stateInfo; if (Thread.CurrentThread.IsBackground) { Console.WriteLine( "background thread: " + state); } else { Console.WriteLine( "foreground thread: " + state); } } } } /* Resulting output: foreground thread: Thread 3 Main thread exits. background thread: Thread 1 background thread: Thread 2 background thread: Thread 4 From runapp, My Thread.ThreadState=Unstarted Calling ThreadCallback My Thread.ThreadState=Running */ |
Tuesday, October 27, 2009
Multithreaded Applications
I wrote the following test program, which makes use of several classes in the System.Threading namespace:
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment