在C#中,System.Threading.Thread类用于处理线程。它允许在多线程应用程序中创建和访问各个线程。在进程中执行的第一个线程称为主线程。
当C#程序开始执行时,将自动创建主线程。使用Thread类创建的线程称为主线程的子线程。
以下是显示如何在C#中创建线程的示例-
using System; using System.Threading; namespace Demo { class Program { static void Main(string[] args) { Thread th = Thread.CurrentThread; th.Name = "MainThread"; Console.WriteLine("This is {0}", th.Name); Console.ReadKey(); } } }
这是另一个示例,显示了如何在C#中管理线程-
using System; using System.Threading; namespace MultithreadingApplication { class ThreadCreationProgram { public static void CallToChildThread() { Console.WriteLine("Child thread starts"); //线程暂停了5000毫秒 int sleepfor = 5000; Console.WriteLine("Child Thread Paused for {0} seconds", sleepfor / 1000); Thread.Sleep(sleepfor); Console.WriteLine("Child thread resumes"); } static void Main(string[] args) { ThreadStart childref = new ThreadStart(CallToChildThread); Console.WriteLine("In Main: Creating the Child thread"); Thread childThread = new Thread(childref); childThread.Start(); Console.ReadKey(); } } }
输出结果
In Main: Creating the Child thread Child thread starts Child Thread Paused for 5 seconds Child thread resumes