Using the Main Thread


As mentioned at the start of this chapter, all C# programs have at least one thread of execution, called the main thread, which is given to the program automatically when it begins running. The main thread can be handled just like all other threads.

To access the main thread, you must obtain a Thread object that refers to it. You do this through the CurrentThread property, which is a member of Thread. Its general form is shown here:

 public static Thread CurrentThread{ get; }

This method returns a reference to the thread in which it is called. Therefore, if you use CurrentThread while execution is inside the main thread, you will obtain a reference to the main thread. Once you have this reference, you can control the main thread just like any other thread.

The following program obtains a reference to the main thread, and then gets and sets the main thread’s name and priority:

 // Control the main thread. using System; using System.Threading; class UseMain {   public static void Main() {     Thread thrd;     // Get the main thread.     thrd = Thread.CurrentThread;     // Display main thread's name.     if(thrd.Name == null)       Console.WriteLine("Main thread has no name.");     else       Console.WriteLine("Main thread is called: " + thrd.Name);     // Display main thread's priority.     Console.WriteLine("Priority: " + thrd.Priority);     Console.WriteLine();     // Set the name and priority.     Console.WriteLine("Setting name and priority.\n");     thrd.Name = "Main Thread";     thrd.Priority = ThreadPriority.AboveNormal;     Console.WriteLine("Main thread is now called: " +                        thrd.Name);     Console.WriteLine("Priority is now: " +                        thrd.Priority);   } }

The output from the program is shown here:

 Main thread has no name. Priority: Normal Setting name and priority. Main thread is now called: Main Thread Priority is now: AboveNormal

One word of caution: You need to be careful about what operations you perform on the main thread. For example, if you add this call to Join( ) to the end of Main( ):

 thrd.Join();

the program will never terminate because it will be waiting for the main thread to end!




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net