这里我们讲一下C#编程之线程使用: 线程是程序中独立的指令流。
对于C#和.NET基类为开发多线程应用程序所提供的的支持。线程的使用常用是通过Thread和ThreadPool类来创建与使用。
利用Thread处理线程:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading; 6 7 namespace ThreadPool 8 { 9 class Program 10 { 11 static int interval; 12 static void Main(string[] args) 13 { 14 Console.Write("interval to display results at?> "); 15 interval = int.Parse(Console.ReadLine()); 16 17 Thread thisThread = Thread.CurrentThread; 18 thisThread.Name = "CurrentThread"; 19 ThreadStart workerStart = new ThreadStart(StartMethod); 20 21 Thread workdThread = new Thread(workerStart); 22 workdThread.Name = "workThread"; 23 workdThread.Start(); 24 DispalyNumbers(); 25 Console.WriteLine("Main Thread finished."); 26 Console.ReadLine(); 27 } 28 static void StartMethod() 29 { 30 DispalyNumbers(); 31 Console.WriteLine("worker thread finished."); 32 } 33 static void DispalyNumbers() 34 { 35 Thread thisThread = Thread.CurrentThread; 36 string name = thisThread.Name; 37 Console.WriteLine(name + ": current culture= " + thisThread.CurrentCulture); 38 for (int i = 1; i < 8 * interval; i++) 39 { 40 if(i%interval==0) 41 { 42 Console.WriteLine(name + ":count has reached " + i); 43 } 44 } 45 } 46 } 47 }
运行输入数字:
如下利用ThreadPool类创建线程:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading; 6 7 namespace ThreadDemo 8 { 9 class Program 10 { 11 static int interval; 12 static void Main(string[] args) 13 { 14 Console.Write("interval to display results at?>"); 15 interval = int.Parse(Console.ReadLine()); 16 ThreadPool.QueueUserWorkItem(new WaitCallback(StartMethod)); 17 Thread.Sleep(100); 18 ThreadPool.QueueUserWorkItem(new WaitCallback(StartMethod)); 19 Console.ReadLine(); 20 } 21 static void StartMethod(object stateInfo) 22 { 23 //todo your code here 24 DisplayNumbers("Thread " + DateTime.Now.Millisecond.ToString()); 25 Console.WriteLine("Thread Finished."); 26 } 27 static void DisplayNumbers(string GivenThreadName) 28 { 29 Console.WriteLine("Start thread: " + GivenThreadName); 30 for(int i=1;i<8*interval;i++) 31 { 32 Console.WriteLine("Count has reached: " + i); 33 Thread.Sleep(1000); 34 } 35 } 36 } 37 }