为什么这个程序只是挂起?

时间:2013-08-26 17:32:19

标签: c# .net asynchronous async-await

我有以下程序:

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功能,但总是没有效果。同样,我的解释也没有。

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:3)

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

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

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

它可以正常运作。