ขั้นตอนการสร้างเธรดแบบง่าย:
- สร้างเมธอดที่จะรันในเธรด:
public void myThread() {
for (int i = 0; i < 3; i++) {
Console.WriteLine("My Thread");
}
}
- สร้างออบเจ็กต์ Thread โดยใช้ ThreadStart delegate:
Demo d = new Demo(); Thread thread = new Thread(new ThreadStart(d.myThread));
- เริ่มต้นเธรดด้วย
thread.Start()
ตัวอย่างโค้ดเต็ม
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
class Demo {
public void myThread() {
for (int i = 0; i < 3; i++) {
Console.WriteLine("My Thread");
}
}
}
class NewThread {
public static void Main() {
Demo d = new Demo();
Thread thread = new Thread(new ThreadStart(d.myThread));
thread.Start();
Console.Read();
}
}
ผลลัพธ์
My Thread My Thread My Thread
คำอธิบาย: คลาส Thread ใน namespace System.Threading ใช้สร้างและควบคุมเธรด ThreadStart เป็น delegate ที่ชี้ไปยังเมธอดที่จะรันในเธรดใหม่