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.Task
1[System.Int32]` instead of waiting for 10 secs and return 7 (as I would expect). Must be something obvious that I am missing.
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);
}
I believe you just need to change the 4th line of your example to:
var s = await p.Ten2SevenAsync();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With