wait 立即移至下一条语句
我正在使用新的异步 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.Task
1[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.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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
基于等待的代码的全部要点在于,它确实是“完成后执行下一个内容”(回调),并且不“阻塞当前线程”直到这一切结束”。
因此,您可以从
Ten2SevenAsync
返回一个任务,但该任务尚未完成。将任务写入控制台并不意味着它会等待任务完成。如果您想阻止任务完成:或更明确地说:
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:or more explicitly:
我相信您只需将示例的第四行更改为:
I believe you just need to change the 4th line of your example to:
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 ofs
that will allow you to check whether or not the task has completed, and then retrieve the result.