CÁC GIẢI PHÁP LẬP TRÌNH C# - Trang 136

136
Chương 4: Tiểu trình, tiến trình, và sự đồng bộ

public ThreadExample(int iterations, string message, int delay) {

this.iterations = iterations;

this.message = message;

this.delay = delay;

}

public void Start() {

// Tạo một thể hiện ủy nhiệm ThreadStart

// tham chiếu đến DisplayMessage.

ThreadStart method = new ThreadStart(this.DisplayMessage);

// Tạo một đối tượng Thread và truyền thể hiện ủy nhiệm

// ThreadStart cho phương thức khởi dựng của nó.

Thread thread = new Thread(method);

Console.WriteLine("{0} : Starting new thread.",

DateTime.Now.ToString("HH:mm:ss.ffff"));

// Khởi chạy tiểu trình mới.

thread.Start();

}

private void DisplayMessage() {

// Hiển thị thông báo ra cửa sổ Console với số lần

// được chỉ định (iterations), nghỉ giữa mỗi thông báo

// một khoảng thời gian được chỉ định (delay).

for (int count = 0; count < iterations; count++) {

Console.WriteLine("{0} : {1}",

DateTime.Now.ToString("HH:mm:ss.ffff"), message);

Thread.Sleep(delay);

}

}