Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

await immediately moves to next statement

I am playing with the new Async CTP bits, and I can't get it work with either server-side or just command-line program (and all the examples are either WPF or Silverlight). For example, some trivial code like:

class Program {
    static void Main() {
        Program p = new Program();
        var s = p.Ten2SevenAsync();
        Console.WriteLine(s);
    }

    private async Task<int> Ten2SevenAsync() {
        await TaskEx.Delay(10000);
        return 7;
    }
}

returns immediately and prints System.Threading.Tasks.Task1[System.Int32]` instead of waiting for 10 secs and return 7 (as I would expect). Must be something obvious that I am missing.

like image 632
Felix Avatar asked May 31 '11 05:05

Felix


2 Answers

The whole point of the await-based code is that it is indeed "execute the next stuff when this is finished" (a callback), and not "block the current thread until this has finished".

As such, from Ten2SevenAsync you get back a task, but that task is not yet complete. Writing the task to the console does not mean it waits for it to complete. If you want to block on the task's completion:

static void Main() {
    Program p = new Program();
    var s = p.Ten2SevenAsync();
    Console.WriteLine(s.Result);
}

or more explicitly:

static void Main() {
    Program p = new Program();
    var s = p.Ten2SevenAsync();
    s.Wait();
    Console.WriteLine(s.Result);
}
like image 125
Marc Gravell Avatar answered Oct 20 '22 15:10

Marc Gravell


I believe you just need to change the 4th line of your example to:

var s = await p.Ten2SevenAsync();
like image 43
LorenVS Avatar answered Oct 20 '22 14:10

LorenVS