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