Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีสร้าง Thread ใน C#

Threads คือ กระบวนการเบาๆ (lightweight processes) Thread คือ เส้นทางการทำงานของโปรแกรม สร้างโดยการสืบทอดคลาส Thread แล้วเรียกเมธอด Start() เพื่อเริ่มการทำงานของ child thread

ตัวอย่าง Thread: การเขียนโปรแกรมแบบ concurrent โดยระบบปฏิบัติการสมัยใหม่ ใช้ threads ประหยัด CPU cycle และเพิ่มประสิทธิภาพแอปพลิเคชัน

ตัวอย่าง

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