2

我有以下程序:

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 功能,但总是没有效果。再一次,我无法解释。

4

2 回答 2

9

问题是您使用return new Task(() => Thread.Sleep(1500));的是Task.Run.

new Task实际上并没有启动任务,这将导致await永远不会触发。

相反,请尝试:

private static Task DoIOWorkAsync() {
    Console.WriteLine("Doing work...");
    return Task.Run(() => Thread.Sleep(1500));
}

或者,更好的是:

private static async Task DoIOWorkAsync() {
    Console.WriteLine("Doing work...");
    await Task.Delay(1500);
}
于 2013-08-26T17:37:37.853 回答
3

很简单,你返回了 a Task,但你没有启动它。

如果您按如下方式更改代码:

private static Task DoIOWorkAsync()
{
    Console.WriteLine("Doing work...");
    Task work = new Task(() => Thread.Sleep(1500));
    work.Start();
    return work;
}

它可以按您的预期工作。

于 2013-08-26T17:37:26.933 回答