ขั้นตอนการส่งพารามิเตอร์ให้เธรด:
- เพิ่ม namespace:
using System.Threading; - สร้างเธรดใหม่:
Thread thread = new Thread(threadDemo); - ส่งพารามิเตอร์ด้วย
thread.Start(parameter);
ตัวอย่างโค้ดเต็ม
using System;
using System.Threading;
namespace Sample {
class Demo {
static void Main(string[] args) {
String str = "Hello World!";
// สร้างเธรดใหม่
Thread thread = new Thread(threadDemo);
// ส่งพารามิเตอร์
thread.Start(str);
}
static void threadDemo(object str) {
Console.WriteLine("Value passed to the thread: " + str);
}
}
}
ผลลัพธ์
Value passed to the thread: Hello World!
คำอธิบาย: เมธอดที่รับพารามิเตอร์ต้องมี signature เป็น void MethodName(object obj) พารามิเตอร์จะถูกส่งผ่าน thread.Start() และรับในรูปแบบ object ต้องแปลงชนิดข้อมูล (cast) ก่อนใช้งาน