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

127

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

new AsyncExampleDelegate(LongRunningMethod);

asyncResults.Add(longRunningMethod.BeginInvoke(3000,

"WaitAll 1", null, null));

asyncResults.Add(longRunningMethod.BeginInvoke(2500,

"WaitAll 2", null, null));

asyncResults.Add(longRunningMethod.BeginInvoke(1500,

"WaitAll 3", null, null));

// Tạo một mảng các đối tượng WaitHandle,

// sẽ được sử dụng để đợi tất cả các phương thức

// thực thi bất đồng bộ kết thúc.

WaitHandle[] waitHandles = new WaitHandle[3];

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

waitHandles[count] =

((IAsyncResult)asyncResults[count]).AsyncWaitHandle;

}

// Đợi cả ba phương thức thực thi bất đồng bộ kết thúc.

// Time-out sau 300 mili-giây và hiển thị trạng thái ra

// cửa sổ Console trước khi tiếp tục đợi.

Console.WriteLine("{0} : Waiting until all 3 methods are " +

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

while(!WaitHandle.WaitAll(waitHandles, 300, false)) {

Console.WriteLine("{0} : WaitAll timeout...",

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

}

// Kiểm tra kết quả của mỗi phương thức và xác định

// thời gian phương thức cuối cùng kết thúc.

DateTime completion = DateTime.MinValue;

foreach (IAsyncResult result in asyncResults) {