C# 多线程的等待所有线程结束的一个问题

一次性地Set,其实使用ManualResetEvent就足够了。

来自为知笔记(Wiz)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

usingSystem;

usingSystem.Threading;

namespaceConsoleApplication1

{

classProgram

{

privatestaticAutoResetEvent[] events;

staticvoidMain(string[] args)

{

intthreadNum = 10;

Thread[] thread =newThread[threadNum];

events =newAutoResetEvent[threadNum];

for(inti = 0; i < threadNum; i++)

{

var waithandler =newAutoResetEvent(false);

events[i] = waithandler;

ThreadStart starter =delegate

{

var param =newTuple<string, AutoResetEvent>("test print:"+ i, waithandler);

Print(param);

};

thread[i] =newThread(starter)

{

Name ="thread"+ i.ToString()

};

}

for(inti = 0; i < threadNum; i++)

{

thread[i].Start();

}

WaitHandle.WaitAll(events);

Console.WriteLine("Completed!");

Console.Read();

}

privatestaticvoidPrint(objectparam)

{

var p = (Tuple<string, AutoResetEvent>)param;

Console.WriteLine(Thread.CurrentThread.Name +": Begin!");

Console.WriteLine(Thread.CurrentThread.Name +": Print"+ p.Item1);

Thread.Sleep(300);

Console.WriteLine(Thread.CurrentThread.Name +": End!");

p.Item2.Set();

}

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Threading;

namespaceConsoleApplication1

{

classProgram

{

staticvoidMain(string[] args)

{

var waits =newList<EventWaitHandle>();

for(inti = 0; i < 10; i++)

{

var handler =newManualResetEvent(false);

waits.Add(handler);

newThread(newParameterizedThreadStart(Print))

{

Name ="thread"+ i.ToString()

}.Start(newTuple<string, EventWaitHandle>("test print:"+ i, handler));

}

WaitHandle.WaitAll(waits.ToArray());

Console.WriteLine("Completed!");

Console.Read();

}

privatestaticvoidPrint(objectparam)

{

var p = (Tuple<string, EventWaitHandle>)param;

Console.WriteLine(Thread.CurrentThread.Name +": Begin!");

Console.WriteLine(Thread.CurrentThread.Name +": Print"+ p.Item1);

Thread.Sleep(300);

Console.WriteLine(Thread.CurrentThread.Name +": End!");

p.Item2.Set();

}

}

}