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

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

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

// ủy nhiệm ThreadStart tham chiếu đến DisplayMessage.

Thread thread = new Thread(new ThreadStart(DisplayMessage));

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

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

// Khởi chạy tiểu trình thứ hai.

thread.Start();

// Lặp và xử lý lệnh do người dùng nhập.

char command = ' ';

do {

string input = Console.ReadLine();

if (input.Length > 0) command = input.ToUpper()[0];

else command = ' ';

switch (command) {

case 'S':

// Tạm hoãn tiểu trình thứ hai.

Console.WriteLine("{0} : Suspending second thread.",

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

thread.Suspend();

break;

case 'R':

// Phục hồi tiểu trình thứ hai.

try {

Console.WriteLine("{0} : Resuming second " +

"thread.",

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

thread.Resume();