เธรดเป็นกระบวนการที่มีน้ำหนักเบา เธรดถูกกำหนดให้เป็นเส้นทางการดำเนินการของโปรแกรม เธรดถูกสร้างขึ้นโดยการขยายคลาสเธรด คลาสเธรดแบบขยายจะเรียกเมธอด Start() เพื่อเริ่มการดำเนินการเธรดย่อย
ตัวอย่างของเธรด:ตัวอย่างทั่วไปของการใช้เธรดคือการใช้งานการเขียนโปรแกรมพร้อมกันโดยระบบปฏิบัติการสมัยใหม่ การใช้เธรดช่วยประหยัดการสูญเสียของวงจร CPU และเพิ่มประสิทธิภาพของแอปพลิเคชัน
ต่อไปนี้เป็นตัวอย่างที่แสดงวิธีการสร้างเธรด
ตัวอย่าง
using System;
using System.Threading;
namespace Demo {
class Program {
public static void ThreadFunc() {
Console.WriteLine("Child thread starts");
}
static void Main(string[] args) {
ThreadStart childref = new ThreadStart(ThreadFunc);
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