wait 立即移至下一条语句

发布于 2024-11-10 17:49:13 字数 483 浏览 4 评论 0原文

我正在使用新的异步 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 (如我所料)。一定是我缺少的明显的东西。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

独木成林 2024-11-17 17:49:13

基于等待的代码的全部要点在于,它确实是“完成后执行下一个内容”(回调),并且“阻塞当前线程”直到这一切结束”。

因此,您可以从 Ten2SevenAsync 返回一个任务,但该任务尚未完成。将任务写入控制台并不意味着它会等待任务完成。如果您想阻止任务完成:

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

或更明确地说:

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

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);
}
站稳脚跟 2024-11-17 17:49:13

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

var s = await p.Ten2SevenAsync();

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

var s = await p.Ten2SevenAsync();
别把无礼当个性 2024-11-17 17:49:13

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

s is a reference to an asynchronous task. I haven't played with this myself yet so I'm not sure of the syntax, but there will be members of s that will allow you to check whether or not the task has completed, and then retrieve the result.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文