在调用 Wait 之前访问任务上的结果实际上有什么作用? [英] What does accessing a Result on a Task before calling Wait actually do?
问题描述
var task = Task.Run(() => DoSomeStuff()).Result;
幕后发生了什么?
我做了一个小测试:
using System;
using System.Threading.Tasks;
public class Program
{
public static void Main()
{
var r = Task.Run( () => {Thread.Sleep(5000); return 123; }).Result;
Console.WriteLine(r);
}
}
它在 5 秒后打印123".那么访问 Task
上的任何此类属性是否可以作为调用 Task.Wait()
的快捷方式,即这样做是否安全?
It prints "123" after 5s. So does accessing any such property on Task
act as a shortcut to calling Task.Wait()
i.e. is this safe to do?
以前我的代码称为 Task.Delay(5000)
,它立即返回123".我在我的问题中解决了这个问题,但将其留在这里作为评论和答案参考.
Previously my code called Task.Delay(5000)
which returned "123" immediately. I fixed this in my question but leave this here as comments and answers reference it.
推荐答案
那么访问
Task
上的任何此类属性是否可以作为调用Task.Wait()
的快捷方式?
So does accessing any such property on
Task
act as a shortcut to callingTask.Wait()
?
是的.
来自 文档:
访问[Result
]属性的get访问器会阻塞调用线程,直到异步操作完成;它相当于调用 等待 方法.
Accessing the [
Result
] property's get accessor blocks the calling thread until the asynchronous operation is complete; it is equivalent to calling the Wait method.
然而,您的测试并没有像您想象的那样做.
However, your test doesn't do what you think it does.
Task.Delay(..)
返回一个在指定时间后完成的 Task
.它不会阻塞调用线程.
Task.Delay(..)
returns a Task
which completes after the specified amount of time. It doesn't block the calling thread.
所以 () =>{ Task.Delay(5000);返回 123;}
只需创建一个新的Task
(将在5 秒内完成),然后将其丢弃并立即返回123
.
So () => { Task.Delay(5000); return 123; }
simply creates a new Task
(which will complete in 5 seconds), then throws it away and immediately returns 123
.
您可以:
- 通过执行
Task.Delay(5000).Wait()
(与Thread.Sleep(5000)
做同样的事情)阻止调用线程立> - 异步等待
Task.Delay
返回的Task
完成:Task.Run(async() => { await Task.Delay(5000); 返回 123; })
- Block the calling thread, by doing
Task.Delay(5000).Wait()
(which does the same thing asThread.Sleep(5000)
) - Asynchronously wait for the
Task
returned fromTask.Delay
to complete:Task.Run(async () => { await Task.Delay(5000); return 123; })
这篇关于在调用 Wait 之前访问任务上的结果实际上有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!