System.Threading and System.Threading.Thread main types to work with threads directly
example
1 2 3 4 5 6 7 8 9 10 11 12 |
static void PrimaryThreadStats() { Thread t = Thread.CurrentThread; t.Name = "PrimaryThread"; Console.WriteLine("Name of current AppDomain:{0}",Thread.GetDomain().FriendlyName); Console.WriteLine("ID of current context:{0}", Thread.CurrentContext.ContextID); Console.WriteLine("ThreadName:{0}", t.Name); Console.WriteLine("Is Alive?:{0}", t.IsAlive); Console.WriteLine("Priority:{0}", t.Priority); Console.WriteLine("ThreadState:{0}", t.ThreadState); Console.ReadLine(); } |
During debugging… we can see what is happening to threads…
Debug > Windows > Threads
ThreadStart Example
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 67 68 69 70 71 72 73 74 75 76 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.Windows.Forms; // add reference to System.Windows.Forms.dll namespace ThreadStats { class Program { static void Main(string[] args) { //PrimaryThreadStats(); Console.WriteLine("*** Amasing Thread App ***\n"); Console.Write("Do you want [1] or [2] threads?"); string threadCount = Console.ReadLine(); Thread primaryThread = Thread.CurrentThread; primaryThread.Name = "Primary"; Console.WriteLine("-> {0} is executing Main()", Thread.CurrentThread.Name); Printer p = new Printer(); switch (threadCount) { case "2": Thread backgroundThread = new Thread(new ThreadStart(p.PrintNumbers)); backgroundThread.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"; } MessageBox.Show("I am buisy!","Work on main thread..."); Console.ReadLine(); } public class Printer { public void PrintNumbers() { Console.WriteLine("-> {0} is executing PrintNumbers()",Thread.CurrentThread.Name); Console.WriteLine("Your Numbers:"); for (int i = 0; i < 10; i++) { Console.Write("{0}, ",i); Thread.Sleep(2000); } Console.WriteLine(); } } static void PrimaryThreadStats() { Thread t = Thread.CurrentThread; t.Name = "PrimaryThread"; Console.WriteLine("Name of current AppDomain:{0}",Thread.GetDomain().FriendlyName); Console.WriteLine("ID of current context:{0}", Thread.CurrentContext.ContextID); Console.WriteLine("ThreadName:{0}", t.Name); Console.WriteLine("Is Alive?:{0}", t.IsAlive); Console.WriteLine("Priority:{0}", t.Priority); Console.WriteLine("ThreadState:{0}", t.ThreadState); Console.ReadLine(); } } } |