Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Again, the explanation eludes me.

like image 706
Xenoprimate Avatar asked Jun 17 '26 15:06

Xenoprimate


1 Answers

The problem is you're using return new Task(() => Thread.Sleep(1500)); instead of Task.Run.

new Task doesn't actually start the task, which will cause the await to never trigger.

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);
}
like image 134
Reed Copsey Avatar answered Jun 20 '26 05:06

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!