简体   繁体   English

直接在任务上等待。 C#

[英]Calling await on the task directly. C#

I am learning await/async right now. 我正在学习等待/异步。 and I have a question: Is there a difference between calling the await directly on the task and call it later? 我有一个问题:直接在任务上调用等待和稍后再调用之间有区别吗?

var task = getAllAsync();
...
var list = await task;

OR 要么

var list = await getAllAsync();

If there is a difference, what is it? 如果有区别,那是什么?

If you await immediately after assigning "task" to a variable there is no difference. 如果在将“任务”分配给变量后立即等待,则没有区别。 If you have code between method call and await-ing you have chance to execute operations in parallel. 如果在方法调用和等待之间有代码,则有机会并行执行操作。

Most tasks are created "hot" - they already have started operation (like reading file). 大多数任务是“热”创建的-它们已经开始运行(例如读取文件)。 As result if you have some code before await that code may execute while operation started by task is going on separately. 结果,如果您在await之前有一些代码,则在由任务启动的操作单独进行时,这些代码可能会执行。 Ie you can start multiple tasks and than wait for all of them to complete - Running multiple async tasks and waiting for them all to complete . 也就是说,您可以启动多个任务,然后等待所有任务完成- 运行多个异步任务并等待它们全部完成

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM