5

我正在使用新的 Async CTP 位,我无法让它与服务器端或命令行程序一起工作(所有示例都是 WPF 或 Silverlight)。例如,一些琐碎的代码,如:

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

立即返回并打印System.Threading.Tasks.Task1[System.Int32]` 而不是等待 10 秒并返回 7(如我所料)。一定是我想念的明显东西。

4

3 回答 3

11

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);
}
于 2011-05-31T05:59:32.230 回答
2

我相信您只需将示例的第 4 行更改为:

var s = await p.Ten2SevenAsync();
于 2011-05-31T05:43:30.393 回答
1

s是对异步任务的引用。我自己还没有玩过这个,所以我不确定语法,但是会有一些成员s允许你检查任务是否已经完成,然后检索结果。

于 2011-05-31T05:44:58.890 回答