public static List<Action> TestData() { var actions = new List<Action>(); for (int i = 0 ; i < 100 ; i++) { int j = i;//编译变量 actions.Add(() => { Console.WriteLine(j+"-"+Thread.CurrentThread.ManagedThreadId); }); } return actions; } public static void Main() { Do(); Console.ReadKey(); } public static async void Do() { foreach (var item in TestData()) { await Task.Run(item); } }
测试输出:
0-3
1-4
2-3
3-4
4-3
5-3
6-4
7-3
8-3
9-5
10-3
11-5
12-3
13-3
14-5
15-3
16-4
17-5
18-4
19-6
20-3
21-6
22-7
23-6
24-3
25-7
26-3
27-6
28-3
29-6
30-3
31-4
32-6
33-3
34-6
35-5
36-3
37-6
38-7
39-6
40-4
41-5
42-6
43-4
44-3
45-6
46-4
47-3
48-5
49-3
50-6
51-4
52-3
53-5
54-4
55-3
56-6
57-4
58-6
59-4
60-5
61-3
62-6
63-4
64-3
65-6
66-4
67-3
68-5
69-4
70-3
71-5
72-4
73-5
74-6
75-3
76-5
77-3
78-4
79-4
80-6
81-4
82-5
83-3
84-4
85-6
86-4
87-6
88-3
89-4
90-6
91-3
92-4
93-5
94-5
95-3
96-5
97-6
98-5
99-6
因为使用 await 所有后面的任务会作为后续任务 即 continuewith 执行,所以输出是有序的。