多线程是C#最有用的功能,它允许对程序的两个或更多部分进行并发编程,以最大程度地利用CPU。程序的每个部分都称为线程。因此,换句话说,线程是进程内的轻量级进程。 C#支持两种类型的线程,如下所示:
- 前景线程
- 后台线程
前景线程
即使主线程离开了进程,该线程仍会继续运行以完成其工作,这种类型的线程称为前台线程。前景线程不在乎主线程是否处于活动状态,它仅在完成其分配的工作时才完成。换句话说,前台线程的寿命不依赖于主线程。
例子:
// C# program to illustrate the
// concept of foreground thread
using System;
using System.Threading;
class GFG {
// Main method
static void Main(string[] args)
{
// Creating and initializing thread
Thread thr = new Thread(mythread);
thr.Start();
Console.WriteLine("Main Thread Ends!!");
}
// Static method
static void mythread()
{
for (int c = 0; c <= 3; c++) {
Console.WriteLine("mythread is in progress!!");
Thread.Sleep(1000);
}
Console.WriteLine("mythread ends!!");
}
}
输出:
Main Thread Ends!!
mythread is in progress!!
mythread is in progress!!
mythread is in progress!!
mythread is in progress!!
mythread ends!!
说明:在上面的示例中, thr线程在主线程结束后运行。所以,THR胎面的生活并不取决于主线程的生命。 thr线程仅在完成分配的任务时才结束其进程。
后台线程
当Main方法离开进程时离开进程的线程,这些类型的线程称为后台线程。换句话说,后台线程的寿命取决于主线程的寿命。如果主线程完成其过程,则后台线程也将结束其过程。
注意:如果要在程序中使用后台线程,则将线程IsBackground property
的值设置为true 。
例子:
// C# program to illustrate the
// concept of Background thread
using System;
using System.Threading;
class GFG {
// Main method
static void Main(string[] args)
{
// Creating and initializing thread
Thread thr = new Thread(mythread);
// Name of the thread is Mythread
thr.Name = "Mythread";
thr.Start();
// IsBackground is the property of Thread
// which allows thread to run in the background
thr.IsBackground = true;
Console.WriteLine("Main Thread Ends!!");
}
// Static method
static void mythread()
{
// Display the name of the
// current working thread
Console.WriteLine("In progress thread is: {0}",
Thread.CurrentThread.Name);
Thread.Sleep(2000);
Console.WriteLine("Completed thread is: {0}",
Thread.CurrentThread.Name);
}
}
输出:
In progress thread is: Mythread
Main Thread Ends!!
说明:在以上示例中,通过将IsBackground的值设为true,使用Thread类的IsBackground属性将thr线程设置为后台线程。如果将IsBackground的值设置为false,则给定线程将充当前台线程。现在,当主线程的进程结束时,thr线程的进程结束。