我有以下程序:
static void Main(string[] args) { RunTest(); }
private static void RunTest() {
DoIOWorkFiveTimesAsync().Wait();
}
private static async Task DoIOWorkFiveTimesAsync() {
for (int i = 0; i < 5; ++i) {
Console.WriteLine("Before: " + i);
await DoIOWorkAsync();
Console.WriteLine("After: " + i);
}
}
private static Task DoIOWorkAsync() {
Console.WriteLine("Doing work...");
return new Task(() => Thread.Sleep(1500));
}
我希望看到:
Before: 1
Doing work...
After: 1
Before: 2
Doing work...
After: 2
Before: 3
Doing work...
After: 3
Before: 4
Doing work...
After: 4
Before: 5
Doing work...
After: 5
但相反,它会:
Before: 1
Doing work...
并且永远不会更进一步。我已经尝试并试图理解 C#5 中的 async/await 功能,但总是没有效果。再一次,我无法解释。