ในการสร้างเธรด ฉันได้สร้างฟังก์ชัน -
public void myThread() {
for (int i = 0; i < 3; i++) {
Console.WriteLine("My Thread");
}
} ฟังก์ชันข้างต้นถูกเรียกเพื่อสร้างเธรดและสร้างตัวแทน ThreadStart ใหม่ -
Demo d = new Demo(); Thread thread = new Thread(new ThreadStart(d.myThread));
ตัวอย่าง
สร้างเธรดอย่างง่ายโดยใช้รหัสต่อไปนี้
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