Để truyền dữ liệu cho luồng khi khởi động, sử dụng delegate ParameterizedThreadStart và phương thức thread.Start(object).
Các bước
- Import namespace:
using System.Threading; - Tạo luồng với
ParameterizedThreadStarttrỏ đến phương thức nhậnobject. - Gọi
thread.Start(tham_số)để truyền dữ liệu.
Mã nguồn
using System;
using System.Threading;
namespace Sample {
class Demo {
static void Main(string[] args) {
string str = "Hello World!";
// Tạo luồng với ParameterizedThreadStart
Thread thread = new Thread(threadDemo);
// Truyền tham số khi Start
thread.Start(str);
}
// Phương thức luồng nhận object
static void threadDemo(object str) {
Console.WriteLine("Giá trị truyền cho luồng: " + str);
}
}
}
Kết quả
Giá trị truyền cho luồng: Hello World!
Ép kiểu an toàn trong phương thức luồng
static void threadDemo(object data) {
if (data is string s) {
Console.WriteLine("Chuỗi nhận được: " + s);
} else if (data is int n) {
Console.WriteLine("Số nguyên nhận được: " + n);
} else {
Console.WriteLine("Kiểu không hỗ trợ: " + data?.GetType().Name);
}
}
Truyền nhiều tham số
Gói vào class, struct, tuple hoặc object anonim:
// Tuple
thread.Start(("Alice", 25, true));
// Class
class ThreadData { public string Name; public int Age; }
thread.Start(new ThreadData { Name = "Bob", Age = 30 });
// Object anonim
thread.Start(new { Name = "Charlie", Age = 35 });
Lưu ý
ParameterizedThreadStartchỉ nhận 1 tham sốobject— cần ép kiểu (cast) bên trong.- Dữ liệu truyền đi nên là immutable hoặc thread-safe để tránh race condition.
- Ưu tiên dùng
Task.Run(() => DoWork(param))(TPL) — tự nhiên hơn, hỗ trợ async/await, exception handling tốt hơn.