简体   繁体   English

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

[英]Why does this program just hang?

I have the following program: 我有以下程序:

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));
    }

I would expect to see: 我希望看到:

  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

But instead, it gets to: 但相反,它得到:

Before: 1
Doing work...

And never gets any further. 永远不会再进一步​​了。 I have tried and tried to understand the async/await features in C#5, but always to no effect. 我试过并尝试了解C#5中的async / await功能,但总是没有效果。 Again, the explanation eludes me. 同样,我的解释也没有。

The problem is you're using return new Task(() => Thread.Sleep(1500)); 问题是你正在使用return new Task(() => Thread.Sleep(1500)); instead of Task.Run . 而不是Task.Run

new Task doesn't actually start the task, which will cause the await to never trigger. new Task实际上并不启动任务,这将导致await永远不会触发。

Instead, try: 相反,尝试:

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

Or, better yet: 或者,更好的是:

private static async Task DoIOWorkAsync() {
    Console.WriteLine("Doing work...");
    await Task.Delay(1500);
}

Simple, you returned a Task , but you didn't start it. 很简单,你返回了一个Task ,但你没有启动它。

If you change your code as follows: 如果您更改代码如下:

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

It works as you would expect. 它可以像你期望的那样工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM