2024年3月9日发(作者:)

using System;

using ing;

public sealed class App

{

// Define an array with two AutoResetEvent WaitHandles.

static WaitHandle[] waitHandles = new WaitHandle[]

{

new AutoResetEvent(false),

new AutoResetEvent(false)

};

// Define a random number generator for testing.

static Random r = new Random();

static void Main()

{

// Queue up two tasks on two different threads;

// wait until all tasks are completed.

DateTime dt = ;

// ine("Main thread is waiting for BOTH tasks to complete.");

serWorkItem(new WaitCallback(DoTask), waitHandles[0]);

serWorkItem(new WaitCallback(DoTask), waitHandles[1]);

l(waitHandles);

// The time shown below should match the longest task.

ine("Both tasks are completed (time waited={0})",

( - dt).TotalMilliseconds);

// Queue up two tasks on two different threads;

// wait until any tasks are completed.

dt = ;

ine();

ine("The main thread is waiting for either task to complete.");

serWorkItem(new WaitCallback(DoTask), waitHandles[0]);

serWorkItem(new WaitCallback(DoTask), waitHandles[1]);

int index = y(waitHandles);

// The time shown below should match the shortest task.

ine("Task {0} finished first (time waited={1}).",

index + 1, ( - dt).TotalMilliseconds);

}

static void DoTask(Object state)

{

AutoResetEvent are = (AutoResetEvent)state;

int time = 1000 * (2, 10);

ine("Performing a task for {0} milliseconds.", time);

(time);

();

}

}

// This code produces output similar to the following:

//

// Main thread is waiting for BOTH tasks to complete.

// Performing a task for 7000 milliseconds.

// Performing a task for 4000 milliseconds.

// Both tasks are completed (time waited=7064.8052)

//

// The main thread is waiting for either task to complete.

// Performing a task for 2000 milliseconds.

// Performing a task for 2000 milliseconds.

// Task 1 finished first (time waited=2000.6528).