Saturday, 6 July 2013

Threading in C#

A C# client program (Console, WPF, or Windows Forms) starts in a single thread created automatically by the CLR and operating system (the “main” thread)


All examples assume the following namespaces are imported: 

using System; 
using System.Threading; 

class ThreadTest
{
     static void Main()
     {
 
         Thread t = new Thread (Write);        //  a new thread 
         t.Start();                                           //   running Write() 

         // Simultaneously, do something on the main thread.       
         for (int i = 0; i < 1000; i++)
             Console.Write ("x");

     }
     static void Write()
     {
         for (int i = 0; i < 1000; i++) Console.Write ("y");
     }
}

Output : 
xxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyy
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
yyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


Properties of a Thread

  • Thread.CurrentThread -> Static method gives the reference of the thread object which is executing the current code.
  • Name           -> Read/Write Property used to get and set the name of a thread
  • ThreadState -> Property used to check the state of a thread.
  • Priority        -> Property used to check for the priority level of a thread.
  • IsAlive         -> Returns a Boolean value stating whether the thread is alive or not.
  • IsBackground -> Returns a Boolean value stating the running in background or foreground.

PriorityLevels of Thread

  • Highest
  • AboveNormal
  • Normal
  • BelowNormal
  • Lowest

No comments:

Post a Comment